简体   繁体   中英

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. All activity pushes itself into the Stack at its onCreate(), and pops itself at 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.

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.

So my question is, why in this scenario the onDestroy() is not being executed right after the finish()?

I would suggest some reading:

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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