Lifecycle.Event.ON_DESTROY is not called in Application
Asked Answered
I

1

6

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?

Irredentist answered 9/2, 2021 at 8:44 Comment(0)
T
9

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.

Tetartohedral answered 9/2, 2021 at 8:48 Comment(1)
Could you show me any example?>Mylor

© 2022 - 2024 — McMap. All rights reserved.