简体   繁体   English

在Activity.finish()之后,onDestroy无法立即执行

[英]onDestroy from activity not executing right after Activity.finish()

So here is the scenario where my doubt dwells: i have a Stack object of Activity in my Application class that will hold reference to all Activities that are currently alive in my App. 因此,在这种情况下,我的疑问仍然存在我的Application类中有一个Activity的Stack对象,该对象将保存对App中当前存在的所有Activity的引用。 All activity pushes itself into the Stack at its onCreate(), and pops itself at onDestroy(). 所有活动将其自身的onCreate()推送到堆栈中,并在onDestroy()上弹出自身。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyApplicationClass.stackOfActivity.add(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    MyApplicationClass.stackOfActivity.pop();
}

At MyApplicationClass (that is the class that extends Application) i created a method to finish the activities that are on the top of the Stack. 在MyApplicationClass(这是扩展Application的类)上,我创建了一种方法来完成堆栈顶部的活动。

static public void popActivitiesFromStack(int  amountOfActivitiesToBePopedOut){
    if(stackOfActivity.size() >= amountOfActivitiesToBePopedOut){
        for(int i = 0; i < amountOfActivitiesToBePopedOut; i++){
            stackOfActivity.peek().finish();
        }
    }
}

The problem is that all iterations from the FOR from "popActivitiesFromStack" are executed before any OnDestroy() is executed , and with that no activity is poped out while the FOR is executed, and every finish() call called in the FOR goes to the same activity. 问题是在执行任何OnDestroy()之前,将执行来自“ popActivitiesFromStack”中FOR的所有迭代,并且在执行FOR时不会弹出任何活动,并且FOR中调用的每个finish()调用都将转到同样的活动。

So my question is, why in this scenario the onDestroy() is not being executed right after the finish()? 所以我的问题是, 为什么在这种情况下,在finish()之后不立即执行onDestroy()?

I would suggest some reading: 我建议阅读:

http://developer.android.com/training/basics/activity-lifecycle/index.html http://developer.android.com/training/basics/activity-lifecycle/index.html

onDestroy() can very well not be executed immediately if the system doesn't need to destroy the activity. 如果系统不需要销毁活动,则onDestroy()可能无法立即执行。

Your assumptions are all wrong :-( 您的假设都是错误的:-(

The lifecycle calls to multiple activities are not executed in any defined or deterministic sequence. 对多个活动的生命周期调用不会以任何定义或确定的顺序执行。

onDestroy() is called on an Activity whenever the framework gets around to cleaning up. 每当框架进行清理时,都会在Activity上调用onDestroy() It may be called immediately, or it may be called much much later. 可以立即调用它,也可以稍后调用它。 You have no control of the timing. 您无法控制时间。

Android maintains the stack of activities in the task, and you can use the Intent flag FLAG_ACTIVITY_CLEAR_TOP to do what you are trying to do. Android会维护任务中的活动堆栈,您可以使用Intent标志FLAG_ACTIVITY_CLEAR_TOP来完成您想做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM