简体   繁体   中英

Android, cancel notification when app is removed from “Recent apps”

In an android app, I create a notification when an app is moved to the background. When the notification is clicked, it moves the application back to the foreground.

The problem I have is in the background, and the user removes the app through "Recent apps" (ie, he swipes it away), the notification stays. How can I capture the swipe event, ie when the app is removed from "Recent apps". I tried onDestroy, but that is not getting triggered.

Added in API level 14 , there is a callback method onTaskRemoved . This is called if the service is currently running and the user has removed a task that comes from the service's application.

So in your Service class, who is posting the notification, you can override this method and stop the running service which is responsible for showing the notification.

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        stopSelf();
    }

With above code inside your Service call, as soon as user removes the app through "Recent apps" (ie, he/she swipes it away), the onTaskRemoved callback for this service will be invoked and with stopSelf() app is stopping the service responsible for showing/posting the notification.

Consequently the posted notification will be removed by the system.

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