gpt4 book ai didi

java - 如果 onDestroy 之后有一个 Instruction,这个 Instruction 会被执行吗?

转载 作者:行者123 更新时间:2023-11-29 19:05:50 26 4
gpt4 key购买 nike

在 Destroy 之后,我打印了一条 Log 语句,Log 是否会显示为应用程序已经被销毁并且在应用程序被销毁后无法执行任何指令。

    @Override
protected void onDestroy() {
super.onDestroy();
Log.v(TestActivity,"App is currntly getting destroyed")
}

那么会打印“App is currently getting destroyed”吗?如果它不会被打印,那么我如何在 onDestroy 方法中执行代码?

最佳答案

您问题的答案是“视情况而定”。

reference documentation表示 onDestroy 不能保证被调用。

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. 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.

所以,是的,您的消息将被调用除非 Android 首先销毁进程

文档还说您必须调用父类(super class)实现...

If you override this method you must call through to the superclass implementation.

...但它没有说明调用的顺序。因此,我会查看 Activiy 源代码以了解它在做什么。这是来自 Google SourceonDestroy 的(最新版本)源代码.

protected void onDestroy() {
mCalled = true;
// dismiss any dialogs we are managing.
if (mManagedDialogs != null) {
final int numDialogs = mManagedDialogs.size();
for (int i = 0; i < numDialogs; i++) {
final ManagedDialog md = mManagedDialogs.valueAt(i);
if (md.mDialog.isShowing()) {
md.mDialog.dismiss();
}
}
mManagedDialogs = null;
}
// close any cursors we are managing.
synchronized (mManagedCursors) {
int numCursors = mManagedCursors.size();
for (int i = 0; i < numCursors; i++) {
ManagedCursor c = mManagedCursors.get(i);
if (c != null) {
c.mCursor.close();
}
}
mManagedCursors.clear();
}
// Close any open search dialog
if (mSearchManager != null) {
mSearchManager.stopSearch();
}
}

虽然这可能随时改变,但我们可以看到父类(super class)中的 onDestroy 将清理资源(如文档所述)。那么,您的 onDestroy 实现是否依赖于这些资源中的任何一个?这将决定您的代码应该在 super.onDestroy() 之前被调用。如果不是,那么顺序无关紧要(除了你的老师已经告诉你使用什么顺序)。

关于java - 如果 onDestroy 之后有一个 Instruction,这个 Instruction 会被执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47261991/

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