Android onDestroy() 方法未按预期工作

标签 android ondestroy

我用 onDestroy()方法,我的代码没有完成:

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (int i = 0 ; i < 10; i++) {
            Toast.makeText(this, "Destroy " + i, Toast.LENGTH_SHORT).show();
        }
    }
for循环在索引 2 处停止。为什么循环没有结束?

最佳答案

首先是documentationonDestroy()方法:

should not be used to do things that are intended to remain around after the process goes away.


和:

This method is usually implemented to free resources like threads that are associated with an activity


也在 docs on the Activity 的开头有一个注意,方法onDestroy()onStop()killable :

methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.


并且建议使用 onPause()方法而不是那些可以杀死的方法。
因此,onDestroy() 显然存在一些 android 内部超时。如果没有太长的时间发生在其中,那么它可能会控制函数,如果它发生了,那么它可能会终止执行。这是我的猜测。
根据文档中的内容,我将避免使用此方法来执行您在此处所做的事情,我会尝试使用 onPause()代替方法。
如果要执行代码 仅限 当应用程序完成时,请使用 isFinishing()方法来检查它。 docs推荐这种方法:

Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing.

关于Android onDestroy() 方法未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68088944/

相关文章:

android被销毁时是否有任何 View 回调?

android - 无法启动 Activity ComponentInfo{Activity} : android. view.InflateException: Binary XML file line Error inflating class fragment

java - 使用权限与使用功能

android - 如何组合两个独立的android样式来创建一个新的

Android 在 onDestroy() 时启动另一个 Activity;

android - onDestroy() 或 finish() 是否真的终止了 Activity ?

android - Android 权限处理的 Dexter 库总是触发 onPermissionDenied 回调

Android - ListView 中项目的进入动画

android - 向 Android Activity 注册 "onDestroy event handler"

java - 退出时的后退按钮会产生强制关闭错误