Gabriel Gedler
Gabriel Gedler

Reputation: 43

Managing android's backstack

I have an activity hierarchy and I have a button that allows me to go from activity D to activity B.

image

The thing is that going to B from D would leave C on the backstack, so if I do A->C->D->B and then press back it would send me to C, and not to A (which is what I want).

Is there a way to delete C when I click on the button from B, or is there some kind of workaround?

Upvotes: 4

Views: 74

Answers (2)

David Wasser
David Wasser

Reputation: 95578

Consider using A as a dispatcher. When you want to launch B from D and finish C in the process, do this in D:

// Launch A (our dispatcher)
Intent intent = new Intent(this, A.class);
// Setting CLEAR_TOP ensures that all other activities on top of A will be finished
//  and setting SINGLE_TOP ensures that a new instance of A will not
//  be created (the existing instance will be reused and onNewIntent() will be called)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Add an extra telling A that it should launch B
intent.putExtra("startB", true);
startActivity(intent);

in A.onNewIntent() do this:

@Override
protected void onNewIntent(Intent intent) {
    if (intent.hasExtra("startB")) {
        // Need to start B from here
        startActivity(new Intent(this, B.class));
    }
}

Upvotes: 1

TooManyEduardos
TooManyEduardos

Reputation: 4404

I don't know the specifics of how you're calling B, C and D or what data is getting passed around, but you can close C when you call D if you want.

In C, when starting D, you could do this:

Intent intent = new Intent(this, D.class);
startActivity(intent);
finish();

The finish will close C after starting D.

Again, without much info this is just a shot in the dark though.

Upvotes: 0

Related Questions