Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modification of the back stack in Android

I would like to modify the back stack in my Android application as such:

Right now, here is the flow:

A -> B -> C -> D -> E -> F

I want to be able to modify the back stack, so that when the user goes to activity F, D and E are erased from the stack. so the flow is F -> C if the user hits the back.

Also, from F, the user is able to go to activity B, this should erase C, D, E, and F as well.

I've seen some information on being able to clear the stack, or remove the top item, but I want to remove a number of items from the stack, when an activity is triggered.

Any help is appreciated, thanks very much.

like image 823
mwrazam Avatar asked Jul 06 '12 17:07

mwrazam


1 Answers

You can build an intent with the flag intent.FLAG_ACTIVITY_CLEAR_TOP from F to C. Then you will have to call startActivity() with the intent and trigger this to occur onBackPressed or something similar.

Intent i = new Intent(this, C.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i)

See this answer, which also deals with ensuring that C won't be restarted when you navigate back to it: https://stackoverflow.com/a/11347608/1003511

What FLAG_ACTIVITY_CLEAR_TOP will do is go go back to the most recent instance of activity C on the stack and then clear everything which is above it. However, this can cause the activity to be re-created. If you want to ensure it will be the same instance of the activity, use FLAG_ACTIVITY_SINGLE_TOP as well. From the documentation:

The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().

Edit: Here is a code sample similar to what you want to do:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Intent a = new Intent(this, C.class);
        a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(a);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

code sample source: https://stackoverflow.com/a/9398171/1003511

like image 99
matt5784 Avatar answered Oct 12 '22 17:10

matt5784