Android onDestroy() 方法未按预期工作
Android onDestroy() method not working as expected
我用的是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 处停止。为什么循环没有结束?
首先 documentation 说 onDestroy()
方法:
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()
方法而不是那些可杀死的方法。
所以显然 android 函数有一些 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.
@sweak 的回答几乎解释了为什么你不应该这样做。但是,如果您热衷于这样做。你可以像下面那样做,它将完成 for 循环并给出所有 10 个祝酒词的输出。
@Override
public void onDestroy() {
for (int i = 0 ; i < 10; i++) {
Toast.makeText(this, "Destroy " + i, Toast.LENGTH_SHORT).show();
}
super.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 处停止。为什么循环没有结束?
首先 documentation 说 onDestroy()
方法:
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()
方法而不是那些可杀死的方法。
所以显然 android 函数有一些 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.
@sweak 的回答几乎解释了为什么你不应该这样做。但是,如果您热衷于这样做。你可以像下面那样做,它将完成 for 循环并给出所有 10 个祝酒词的输出。
@Override
public void onDestroy() {
for (int i = 0 ; i < 10; i++) {
Toast.makeText(this, "Destroy " + i, Toast.LENGTH_SHORT).show();
}
super.onDestroy();
}