简体   繁体   English

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

[英]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).我想在用户退出应用程序时调用一些方法(请参阅12以获得帮助)。

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 .除了ON_DESTROY之外,这些事件都会被触发。

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

Probably Application doesn't clean up from memory.可能Application没有从 memory 中清除。 If I swipe the application from recent list or force stop, it won't fire destroy event.如果我从最近的列表中滑动应用程序或强制停止,它不会触发destroy事件。 Maybe these events work right in an Activity .也许这些事件在Activity中正常工作。 How to catch destroy event in the Application ?如何在Application中捕获destroy事件?

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.您可以将此 LifecycleOwner 视为所有活动的组合,除了 Lifecycle.Event.ON_CREATE 将被调度一次并且 Lifecycle.Event.ON_DESTROY 永远不会被调度。

So there is no way to process onDestroy in application.所以没有办法在应用程序中处理onDestroy

Alternatively, you can try to use onTaskRemoved callback of Service class to catch the moment when the app is removed from recents.或者,您可以尝试使用Service class 的onTaskRemoved回调来捕捉应用程序从最近删除的时刻。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM