dvtoever dvtoever - 17 days ago 8
Android Question

Android: Unable to cancel repeating alarm

I am creating a repeating alarm. This works fine using the following code:

Intent intent = new Intent(this.ctx, AlarmReceiver.class);
intent.setAction("" + notificationId);
intent.putExtra(AlarmReceiver.TITLE, alarmTitle);
intent.putExtra(AlarmReceiver.SUBTITLE, alarmSubTitle);
intent.putExtra(AlarmReceiver.TICKER_TEXT, alarmTicker);
intent.putExtra(AlarmReceiver.NOTIFICATION_ID, notificationId);

PendingIntent sender = PendingIntent.getBroadcast(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = getAlarmManager();
am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, 60000, sender);


Now I want to cancel an existing notification message (which pops up every minute for testing purposes), I invoke the following code, passing it an identical notificationId:

Intent intent = new Intent(this.ctx, AlarmReceiver.class);
intent.setAction("" + notificationId);
PendingIntent pi = PendingIntent.getService(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

AlarmManager am = getAlarmManager();
try {
am.cancel(pi);

} catch (Exception e) {
Log.e(PLUGIN_NAME, "AlarmManager update was not canceled. " + e.toString());
}


I see that
pi != null
, however the notification keeps coming and is not being cancelled. Both code snippets reside in the same class.

Basically I have two questions:
- How can I cancel a single alarm using its unique ID?
- How can I cancel all alarms, regardless of the ID?

UPDATE: I found that posting my issue here helps to get my mind straight. Changing the cancel code from:

PendingIntent sender = PendingIntent.getService( ... )


To:

PendingIntent sender = PendingIntent.getBroadcast( ... )


Helps to solve question 1. However the code to cancel all events, still does not work:

Intent intent = new Intent(this.ctx, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

AlarmManager am = getAlarmManager();
am.cancel(pi);

Answer

I'm a noob here. But I think if you want to cancel the alarm, you have to use the exact same instance of PendingIntent. That means "their action, data, type, class, and categories are the same" as defined by filterEquals(Intent) . Therefore, you need to use the same requestCode here, not 0. Maybe you could use a list to store the Notification Ids, and iterate them to cancel all alarms.

Comments