Search code examples
androidandroid-activityback-stack

Android How can I "jump to another branch" in the Activity back stack "tree"?


Let's say I've got a stack like this: A->B->C->D->E and there's an action in E that pops E, D, C and starts F so that I end up with A->B->F.

How can I build such a back stack? Could I use startActivity B with FLAG_ACTIVITY_CLEAR_TOP followed by startActivity F? Wouldn't the first startActivity close E before he could add F? How could I, for example, have A->B->C and an action in C change it to A->D->E? Can I use PendingIntent with TaskStackBuilder to do so?

Thanks in advance! (Btw, this is my first question here!)


Solution

  • To clear the stack back to B and then start F, do this:

    Intent intent = new Intent(this, B.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("startF", true);
    startActivity(intent);
    

    In B.onNewIntent() do this:

    if (intent.hasExtra("startF") {
        Intent startF = new Intent(this, F.class);
        startActivity(startF);
    }
    

    You can use this concept all over the place to go back in the stack to a certain Activity, and tell that Activity what new Activity to launch.