Sampada
Sampada

Reputation: 129

How to get notified when the application is closed in 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 ?

Upvotes: 11

Views: 5644

Answers (1)

earthw0rmjim
earthw0rmjim

Reputation: 19427

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);

Upvotes: 15

Related Questions