문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top