topher
topher

Reputation: 1397

Customizing Back Stack in Android Activities

Consider there is one activity, named Activity S.
Then there will be many activities, say 10 activities, named A, B, C, ..., J.

How can I achieve this:
From those A--J activities, when the back button is pressed, always go back to activity S.
Regardless of the ordering or how the activities are created.

For example:
Starting from S, go to B, then D, then G.
In activity G, press back button, and will go back to S.

== EDIT ==
Should I use Activity.finish() method when leaving all A--J activities ?

Upvotes: 0

Views: 71

Answers (2)

codeMagic
codeMagic

Reputation: 44571

You could accomplish this in different ways depending on the exact result you desire. You could add the following line to your <activity> tags in your manifest.xml for those Activities

android:noHistory="true"

or use an Intent flag when overrdiing onBackPressed() in each

@Override
public void onBackPressed()
{
    Intent i = new Intent(CurrentActivity.this, S.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);`
    startActivity(i);
    super.onBackPressed();
}

this will clear the other Activities from the stack and return you to S.

If you want to keep the Activities on the stack while returning to S then you can change the flag used

 @Override
public void onBackPressed()
{
    Intent i = new Intent(CurrentActivity.this, S.class);
    i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);`
    startActivity(i);
    super.onBackPressed();
}

The last way will bring S to the front and keep the other Activities on the stack which I don't think is what you want but just another option. You will probably want one of the first two ways.

Upvotes: 2

Jitender Dev
Jitender Dev

Reputation: 6925

You have to do like this to achieve, Set a flag that will Clear every activity from stack and pass intent to S.class, like this

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

    Intent intent=new Intent(this,S.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

Upvotes: 1

Related Questions