I am using the alarmManager to set up multiple alarms within my application and have run into an issue. When setting the PendingIntent this way:
timerAlarmIntent = PendingIntent.getBroadcast(myContext, 0, alarmIntent, 0);
myAM.set(AlarmManager.RTC_WAKEUP, alarmTime, timerAlarmIntent);
Where the requestCode is set to 0 (beside the context in getBroadcast) I can use:
myAM.cancel(timerAlarmIntent);
to cancel any amount of alarms I set in the application. However, each alarm I set overwrites the last so only one alarm ends up going off. If I set the requestCode to a unique number such as:
timerAlarmIntent = PendingIntent.getBroadcast(myContext, i, alarmIntent, 0);
myAM.set(AlarmManager.RTC_WAKEUP, alarmTime, timerAlarmIntent);
Where i is set to a unique id number for each alarm using a for loop. This way all alarms run fine, but I cannot cancel the alarms because only one alarm will actually cancel when I run:
myAM.cancel(timerAlarmIntent);
How do I set the requestCode to a unique number and also have the option to cancel it?
The code I ended up using to solve the problem is:
timerAlarmIntent = PendingIntent.getBroadcast(myContext, i, alarmIntent, 0);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
intentArray.add(timerAlarmIntent);
myAM.set(AlarmManager.RTC_WAKEUP, alarmTime, timerAlarmIntent);
To cancel the PendingIntents I set up the following method:
private void cancelAlarms(){
if(intentArray.size()>0){
for(int i=0; i<intentArray.size(); i++){
myAM.cancel(intentArray.get(i));
}
intentArray.clear();
}
}
Why don’t you store timerAlarmIntent objects in a list and cancel them in a loop when needed ?
Regards,
Stéphane