Search code examples
androidapplication-lifecycle

Lifecycle.Event.ON_DESTROY is not called in Application


I want to call some method when a user exits an application (see 1, 2 for help).

class BaseApplication : Application(), LifecycleObserver {

    override fun onCreate() {
        super.onCreate()

        // Register observer.
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) 
    fun init() {
        println("*** called onCreate()")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START) 
    fun LibOnStart() {
        println("*** called onStart()")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP) 
    fun LibOnStop() {
        println("*** called onStop()")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) 
    fun LibOnResume() {
        println("*** called onResume()")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) 
    fun LibOnPause() {
        println("*** called onPause()")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 
    fun cleanup() {
        println("*** called onDestroy()")
    }
}

These events are fired except ON_DESTROY.

I/System.out: *** called onPause() of Activity
I/System.out: *** called onStop() of Activity

Probably Application doesn't clean up from memory. If I swipe the application from recent list or force stop, it won't fire destroy event. Maybe these events work right in an Activity. How to catch destroy event in the Application?


Solution

  • Documentation claims that

    You can consider this LifecycleOwner as the composite of all of your Activities, except that Lifecycle.Event.ON_CREATE will be dispatched once and Lifecycle.Event.ON_DESTROY will never be dispatched.

    So there is no way to process onDestroy in application.

    Alternatively, you can try to use onTaskRemoved callback of Service class to catch the moment when the app is removed from recents.