I have a service running in my Android app. This service was started using an AlarmManager with a repeating alarm. When a certain event occurs, the service sends out a broadcast, which is received within a Fragment. There the alarm is canceled (alarm.cancel(pendingIntent)).
So far, so good. But what do I do if the activity/fragment gets destroyed? How can I still cancel the service?
Just call this alarm.cancel()
with the same pendingIntent
you've used to start it at the onDestroy
method of Activity/Fragment:
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent)
From the description of cancel()
method:
Remove any alarms with a matching Intent
. Any alarm, of any type, whose Intent
matches this one (as defined by filterEquals(Intent)
), will be canceled.