Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notified when the application is closed in Android

Tags:

android

I want to show up a Notification when my app is removed from the recent apps list.

I've tried putting code for that in onStop() and onDestroy() but neither works . onStop() is called as soon as the app is closed (though it is still in the recent app list).

Can anyone tell which method is called when app is removed from recent app list or any way in which this need can be accomplished ?

like image 484
Sampada Avatar asked Jul 09 '16 11:07

Sampada


People also ask

How do I get notifications when an app is closed Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

This answer is outdated and most likely will not work on devices with API level 26+ because of the background service limitations introduced in Oreo.

Original answer:

When you swipe an app out of Recents, its task get killed instantly. No lifecycle methods will be called.

To get notified when this happens, you could start a sticky Service and override its onTaskRemoved() method.

From the documentation of onTaskRemoved():

This is called if the service is currently running and the user has removed a task that comes from the service's application.

For example:

public class StickyService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d(getClass().getName(), "App just got removed from Recents!");
    }
}

Registering it in AndroidManifest.xml:

<service android:name=".StickyService" />

And starting it (e.g. in onCreate()):

Intent stickyService = new Intent(this, StickyService.class);
startService(stickyService);
like image 95
earthw0rmjim Avatar answered Oct 15 '22 05:10

earthw0rmjim