gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:08:37 27 4
gpt4 key购买 nike

我用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com