Search code examples
androidduplicatesalarmmanagerandroid-pendingintent

How to cancel multiple alarms with duplicate PendingIntent at once?


I am setting multiple alarms which will have the exact same PendingIntent object, but their time of going off is different. If I cancel one alarm by providing the same Intent object to PendingIntent, and pass this to AlarmManager.cancel(), will it cancel all the alarms (i.e. with different starting times) or will it exhibit some other behavior?

Here is the code:

while(size != 0)
{
    timeToSet = getNewTime(); //gets calendar object
    Intent intent = new Intent(this, MyAlarmReceiver.class);
    intent.putExtra("uniqueid", uuid);
    intent.putExtra("vibrate", myalarm.getVibrate());
    intent.putExtra("important", myalarm.getImportant());
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(),      
                                       0, intent, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeToSet.getTimeInMillis(), 604800000, pendingIntent);

    size--;
}

So the Intent object is same for all the alarms, but the time is different. Now when I cancel these alarms:

Intent intent = new Intent(this, MyAlarmReceiver.class);
intent.putExtra("uniqueid", uuid);
intent.putExtra("vibrate", myalarm.getVibrate());
intent.putExtra("important", myalarm.getImportant());
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);

Will all the alarms get cancelled? That is what I want it to do. I could use a different requestCode in every PendingIntent, but it will be better if all of them get cancelled as I dont want to maintain and store these extra requestCodes.

Thanks!


Solution

  • If you have a predefined amount of alarms you can set a unique requestCode (second parameter of getBroadcast) for each alarm. But I'm not sure if that works for you. If you don't specify a requestCode all alarms will be seen as equal by filterEqualsand therefore all alarms will be canceled.