0

So, let's say I had an app that used the same method to schedule multiple one-shot alarms and throw up a notification at the scheduled time for each. I'm fairly certain the method I created to handle this works (although I haven't tested it yet), comparing it to other examples I've found. Anyhow, the one thing that bothers me is something in the documentation.

public void cancel (PendingIntent operation) Since: API Level 1

Remove any alarms with a matching Intent. Any alarm, of any type, whose Intent matches this one (as defined by filterEquals(Intent)), will be canceled.

As this application is designed to have multiple one-shot alarms, I'm wondering if my assumption that since these all came from the same base intent created by the same method, that cancelling one alarm would cancel all of the alarms. If so, how would I go about working around this?

Community
  • 1
  • 1
MowDownJoe
  • 728
  • 1
  • 11
  • 29

1 Answers1

4

You can differentiate between alarms by creating each with a unique id such as:

Intent intent = new Intent(this, AlarmReceiverActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,UNIQUE_ID_GOES_HERE, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pi);

Now, when you want to cancel this alarm, you have to create the same PendingIntent with the same unique id. For example, the following will only cancel alarms that you created with PendingIntent id 1234.

Intent intent = new Intent(this, AlarmReceiverActivity.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 1234, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

am.cancel(pi);

The idea is simple. Keep track of the id's and then use them to cancel their respective alarms. If you create multiple alarms with same id, the most recent one will cancel the previous.

In the end, you can have multiple alarms with the unique PendingIntents but not with same PendingIntent.

Erol
  • 6,478
  • 5
  • 41
  • 55