0

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?

deimos1988
  • 5,896
  • 7
  • 41
  • 57
  • Can't you just send out the broadcast and cancel the alarm right there in the service? – VM4 Apr 09 '14 at 08:22
  • @V M I would like to cancel the alarm within the service, but how would I do that? – deimos1988 Apr 09 '14 at 08:23
  • The same way you are cancelling in the fragment i guess? – VM4 Apr 09 '14 at 08:23
  • I the fragment I have the instance of the AlarmManager, I don't have that in the service however. – deimos1988 Apr 09 '14 at 08:26
  • 1
    Well in the service you have your application context, you can get your manager like this: AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Where context is getApplicationContext(). – VM4 Apr 09 '14 at 08:26
  • @V M Thank you very much, it worked! Unfortunately nikis posted it as an answer, so I can't accept your comment as accepted :) – deimos1988 Apr 09 '14 at 08:57

1 Answers1

1

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.

nikis
  • 11,166
  • 2
  • 35
  • 45