Kirk
Kirk

Reputation: 16255

How to properly cancel pending alarms

I can't seem to find an answer to this, but what is the criteria for passing in a matching PendingIntent to be removed from an alarm? It it based on the just the name like com.blah.package.myclass or do the Extras matter?

For example, I'm doing something like this and all alarms fire the same intent:

    public void setAlarm(Context context, long nextAlarmMillis) {
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.putExtra("alarm", this);
        PendingIntent sender = PendingIntent.getBroadcast(context, 1234 /* unused */, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // Get the AlarmManager service
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(sender);
        am.set(AlarmManager.RTC_WAKEUP, nextAlarmMillis, sender);
    }

What happens is that the Alarm class can be altered, etc and passed in as an Extra. I am canceling the previous alarm, but I'm not sure if it's doing anything or if any left over alarms will remain.

Anyone know for sure?

Upvotes: 1

Views: 223

Answers (1)

xandy
xandy

Reputation: 27421

Following is mentioned in AlarmManager documentation

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

Which, the filterEquals() is defined as:

Determine if two intents are the same for the purposes of intent resolution (filtering). That is, if their action, data, type, class, and categories are the same. This does not compare any extra data included in the intents.

I think the easiest to do is you keep the reference of PendingIntent passed to AlarmManager, and pass it to cancel. Or have a factory method to construct such pi.

Upvotes: 3

Related Questions