绕过 onDestroy() 时是否会删除 Handler 回调?

Will Handler callbacks be removed when onDestroy() is bypassed?

我的应用程序有一个奇怪的行为,即使应用程序处于 closed/killed,处理程序仍保持 运行。我使用了如下内容:

fun xyz() {
    Handler().postDelayed({
        // do stuff
        xyz()
    }, 3000)
}

从互联网上,我了解到拥有一个处理程序更好(而不是每次都创建一个新的处理程序)并且您必须调用 handler.removeCallbacksAndMessages(null) 来清除所有递归回调。在 activity 被销毁后,我使用以下代码清理我的处理程序。

override fun onDestroy() {
    super.onDestroy()
    handler.removeCallbacksAndMessages(null)
}

在Android的Documentation中,它说:

There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

如果系统在没有调用 onDestroy() 的情况下终止了我的 activity 的托管进程,处理程序及其回调是否也会被销毁,还是会在后台保留 运行?

当您调用 postDelayed 时,它将被放入 RunnableMessageQueue of MainThread。正如文档所说 kill the activity's hosting processprocess kill 它意味着里面的所有线程都将被杀死所以你的 Handler kill 也没有 ActivityonDestroy 被调用