简体   繁体   中英

How to cancel alarm manager alarms when user removes the app from recent apps list?

As per a comment in this question : "Standard Android only allows you to remove things from that list on Android 3.0+, and doing so does not affect your AlarmManager events".

I would like to cancel the alarms if the user swipes the app from list of recent apps, but there seems to be no way we can handle the swiping of app from recent apps list where the alarm could be canceled. I have option in the app for the user to cancel the alarm which executes this code :

public static void cancelAlarm() {
        if (alarmUp())
        {
            alarmMgr.cancel(pendingIntent);
        }
  }
  public static boolean alarmUp() {
      return (pendingIntent != null);
  }

But how to cancel the alarm when the app removed forcibly ? I do not want to cancel the alarm when app is closed (by pressing back or home button).

Two steps needed to accomplish this:

  1. Detect the app removal from the recents list. See What Exactly Happens When You Swipe An Android App From the Recent Apps List? . That's the best info I found on the subject.

  2. Cancel the alarm. Your question assumes that the pendingIntent variable still holds an intent constructed earlier. This won't work in an activity that was unloaded. Instead, construct an intent that's "equal to" the original intent ("their action, data, type, class, and categories are the same"), and cancel that one.

这可以通过在Activity OnDestroy()中调用alarm.cancel()轻松实现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM