Android: Get all PendingIntents set with AlarmManager

bluediapente picture bluediapente · Nov 30, 2010 · Viewed 68.4k times · Source

I'm setting an alarm like this:

alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingEvent);

I'm interested in removing all the alarms that where previously set, clearing them.

Is there a way for me to do that or to get all the alarms that are currently set so that I can delete them manually ?

Answer

gilsaints88 picture gilsaints88 · Feb 2, 2012

You don't have to keep reference to it. Just define a new PendingIntent like exactly the one that you defined in creating it.

For example:

if I created a PendingIntent to be fired off by the AlarmManager like this:

Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);

alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDateTime, displayIntent);

Then somewhere in your other code (even another activity) you can do this to cancel:

Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);

alarmManager.cancel(displayIntent);

The important thing here is to set the PendingIntent with exactly the same data and action, and other criteria as well as stated here http://developer.android.com/reference/android/app/AlarmManager.html#cancel%28android.app.PendingIntent%29