Easy way to detect when your app is going to be killed

Recently I needed a way of detecting when the app is going to be killed and execute some operations.

Here is a really easy solution by using an IntentService:

class AppKilledDetectingService: IntentService("AppKilledDetectingService") {
    override fun onHandleIntent(intent: Intent?) {}

    override fun onTaskRemoved(rootIntent: Intent?) {
        // Do your operations before the app is killed

Add the service in the manifest:

<application ...>
    <service android:name=".AppKilledDetectingService" android:stopWithTask="true"/>

And that is all you need to do! 👻

Atanas Dimitrov

Atanas Dimitrov

Plovdiv, Bulgaria