Как я могу настроить несколько будильников в Android?
Пока и благодаря этому сайту я смог настроить будильник, который будет настроен и активен, даже если я выключу свой телефон.
Теперь я настроил будильник, чтобы показать напоминание для события A, и мне нужно приложение, чтобы настроить другой будильник, чтобы показать еще одно напоминание для события B.
Я, должно быть, делаю что-то не так, потому что это только вызывает напоминание о событии А. Кажется, что после настройки любой другой сигнал тревоги понимается как тот же самый.:-(
Вот деталь того, что я делаю в два этапа:
1) Из активности я установил будильник, который в определенное время и дату позвонит получателю
Intent intent = new Intent(Activity_Reminder.this,
AlarmReceiver_SetOnService.class);
intent.putExtra("item_name", prescription
.getItemName());
intent
.putExtra(
"message",
Activity_Reminder.this
.getString(R.string.notif_text));
intent.putExtra("item_id", itemId);
intent.putExtra("activityToTrigg",
"com.companyName.appName.main.Activity_Reminder");
PendingIntent mAlarmSender;
mAlarmSender = PendingIntent.getBroadcast(
Activity_Reminder.this, 0, intent, 0);
long alarmTime = dateMgmt.getTimeForAlarm(pickedDate);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(alarmTime);
// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, alarmTime + 15000,
mAlarmSender);
2) С ресивера звоню в сервис
Bundle bundle = intent.getExtras();
String itemName = bundle.getString("item_name");
String reminderOrAlarmMessage = bundle.getString("message");
String activityToTrigg = bundle.getString("activityToTrigg");
int itemId = Integer.parseInt(bundle.getString("item_id"));
NotificationManager nm = (NotificationManager) context.getSystemService("notification");
CharSequence text = itemName + " "+reminderOrAlarmMessage;
Notification notification = new Notification(R.drawable.icon, text,
System.currentTimeMillis());
Intent newIntent = new Intent();
newIntent.setAction(activityToTrigg);
newIntent.putExtra("item_id", itemId);
CharSequence text1= itemName + " "+reminderOrAlarmMessage;
CharSequence text2= context.getString(R.string.notif_Go_To_Details);
PendingIntent pIntent = PendingIntent.getActivity(context,0, newIntent, 0);
notification.setLatestEventInfo(context, text1, text2, pIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.defaults = Notification.DEFAULT_ALL;
nm.notify(itemId, notification);
Заранее спасибо,
monn3t
2 ответа
Хорошо, когда вы устанавливаете PendingIntent, вы должны назначить ему уникальный идентификатор, если вы хотите идентифицировать его позже (для его изменения / отмены)
static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags)
//Retrieve a PendingIntent that will start a new activity, like calling Context.startActivity(Intent).
static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)
//Retrieve a PendingIntent that will perform a broadcast, like calling Context.sendBroadcast().
Код запроса - это тот идентификатор.
В своем коде вы продолжаете сбрасывать ОДИН ЖЕ PendingIntent, вместо этого каждый раз используйте другой RequestCode.
PendingIntent pIntent = PendingIntent.getActivity(context,uniqueRQCODE, newIntent, 0);
Это должно быть целое число, я полагаю, у вас есть первичный идентификатор (itemId), который может идентифицировать сигнал тревоги A из сигнала тревоги B.
Вы можете настроить несколько будильников, указав другой код запроса в pendingIntent.getBroadcast(......)
Подход, который я использовал для установки нескольких сигналов тревоги, заключается в том, что я создал один сигнал тревоги. Я инициализировал статическое целое число в классе настройки будильника, которое будет увеличиваться каждый раз от моей основной деятельности, когда я нажимаю кнопку "добавить тревогу" в своей основной деятельности. Например
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addAlarmClick(View v) {
AlarmActivity.broadcastCode++;
startActivity(new Intent(this, AlarmActivity.class));
}
}
AlarmActivity.java
public class AlarmActivity extends AppCompatActivity {`
//........
public static int broadcastCode=0;
//........
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this,
broadcastCode, myIntent, 0);
Для упрощения, если вы перечисляете свои аварийные сигналы с помощью RecyclerView,
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), recyclerAdapterAlarm.getItemCount()+1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Меня устраивает.