I've programmed an app with multiple alarms using the AlarmManager. I also have a method which cancels all current/pending alarms. It works well, however if the user closes the app from recents (alarms are still active, as intended), my cancel-alarms-method doesn't work anymore (the app crashes). Is there any solution to this? How can I cancel my alarms after the user has closed the app?
This is what my alarms look like:
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
...
Intent intent = new Intent(this, AlertReceiver.class);
Long cal = new GregorianCalendar().getTimeInMillis() + sms_in_x_minutes * 60 * 1000;
PendingIntent i1 = PendingIntent.getBroadcast(this, intent_id++, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, cal, i1);
intentArray.add(i1);
This is what my cancel-method looks like:
private void cancelAlarms(){
if(intentArray.size()>0){
for(int i=0; i<intentArray.size(); i++){
am.cancel(intentArray.get(i));
}
intentArray.clear();
}
}
My guess is that intentArray
and am
are empty after I close the app, and the PendingIntents
are not saved. But I don't know how to work around that.
Do not keep an array of Pending intents. As you correctly diagnosed, your array is empty after the app is closed which causes a crash when you are trying to access them again.
Set up ONLY the earliest alarm. Save the ID of the alarm to temp storage (e.g SharedPreferences
). (If it is easier, you can also use a constant value for the ID as you now only have one alarm to think about)
When your alarm fires, you can set up the next earliest alarm as the first task that is performed.
If you want to cancel your alarm and have an ID value saved in your SharedPreferences
, use this to recreate the AlarmManager
and cancel the alarm. If there is no ID value then no alarms are set and no cancellation is required.