Lifecycle.Event.ON_DESTROY 未在应用程序中调用

Lifecycle.Event.ON_DESTROY is not called in Application

我想在用户退出应用程序时调用一些方法(请参阅 1, 2 获取帮助)。

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()")
    }
}

除了 ON_DESTROY.

之外,这些事件都会被触发
I/System.out: *** called onPause() of Activity
I/System.out: *** called onStop() of Activity

可能 Application 没有从内存中清除。如果我从最近的列表中滑动应用程序或强制停止,它不会触发 destroy 事件。也许这些事件在 Activity 中有效。如何在 Application 中捕获 destroy 事件?

Documentation 声称

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.

所以无法在应用程序中处理onDestroy

或者,您可以尝试使用 Service class 的 onTaskRemoved 回调来捕捉应用从最近应用中删除的时刻。