activity 完成自身但 onDestroy() 调用这个 activity 发生得太晚了

activity finishes itself but onDestroy() call for this activity happen so late

我在我们的代码中发现了一个错误,我们正在通过

启动 activity(我们称其为 SCREEN_ACTIVITY)
Intent intent = new Intent(SharedIntents.INTENT_SCREEN);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

Android 文档:使用 FLAG_ACTIVITY_NEW_TASK 时,如果您现在开始的 activity 任务已经 运行,则新的 activity不会启动;相反,当前任务将以上次的状态简单地带到屏幕前面。

所以在大多数情况下一切正常。

该屏幕 activity 将在用户单击某些内容时调用 finish()。此外,此屏幕 activity 将通过来自服务的传入事件启动或创建。

6053 I/ScreenActivity(15395): onCreate
6682 E/ScreenActivity(15395): finish() Activity
6832 I/ScreenActivity(15395): onDestroy

7284 I/ScreenActivity(15395): onCreate
7911 E/ScreenActivity(15395): finish() Activity
8063 I/ScreenActivity(15395): onDestroy

10555 I/ScreenActivity(15395): onCreate
13413 E/ScreenActivity(15395): finish() Activity
13701 I/ScreenActivity(15395): onCreate
13799 I/ScreenActivity(15395): onDestroy

最后一个问题。 ScreenActivity 被创建,然后调用 finish() 本身。但问题是 onDestroy 被调用的时间很晚。在此之前,有来自服务器的传入事件并调用 startActivity() 触发新的 ScreenAcitivty onCreate()。问题是 ScreenManager class 保留了 activity 创建和销毁的标志。

该标志在onCreate()回调和onDestroy()回调时设置。 因此,对于第 10555 行和第 13701 行,ScreenManager 设置 createFlag = true。对于第 13799 行,设置 createFlag = false。 在第 13799 行之后出现的事件将假定未创建 activity,并且不会将事件通知给 activity。

希望我对问题的描述对您来说很清楚。 这种场景onStop() 和onDestroy() 在调用finish() 之后这么晚才调用预计会发生吗?如果是,我必须考虑解决方案。 如果没有,那有什么地方可以修改吗?

非常感谢。

onDestroy() 可能会被调用,也可能不会被调用。你不能依赖它一直被调用。来自 docs:

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.

如果您需要知道您的 Activity 是否正在完成,了解它是否正在完成的可靠方法是 isFinishing() 方法。你可以在onPause()中调用它,看看这个暂停是否最终会导致这个Activity被销毁:

@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        // Here  you can be sure the Activity will be destroyed eventually
    }
}

使用处理程序,

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() 
              //enter code here for open an Activity
            }
        },300);

在那之后,我们得到的日志应该是:

onCreate
onStop
onDestroy
onCreate