5

I have 4 activities: Activity A -> activity B -> Activity C -> activity D and I what I want to achieve is to go back from D to A and clear B and C. Is this possible?? How??

Thanks a lot.

Kabuki
  • 147
  • 4
  • 10
  • you want never have Activity B and C in back stack? – miljon Mar 20 '17 at 12:17
  • http://stackoverflow.com/questions/12358485/android-open-activity-without-save-into-the-stack – Quick learner Mar 20 '17 at 12:17
  • If you will NEVER go back to B and C from D, don't save B and C in the back stack, this way, when you press back in D, you will jump straight to A. Do you have to go back to B or C ? If not, I can provide your solution. – JonZarate Mar 20 '17 at 12:21

3 Answers3

8

If the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

Intent intent = new Intent(this, ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Read more here.

Charlie
  • 2,876
  • 19
  • 26
0

If the sequence of activity is fixed (A=>B=>C=>D=>A) then before launching Activity C activity you need to call finish of B, And while launching Activity D call finish of activity C.

startActivityC() 
{
    Intent intent = new Intent(this, C.class);
    ActivityB.this.finish()
    startActivity(intent);
}

From activity D to strart Activity A you can override onBack of ActivityD to start Activity A

@Override
onBack()
{

    Intent intent = new Intent(this, A.class);

    ActivityD.this.finish()
    startActivity(intent);
}
Milind Barve
  • 410
  • 3
  • 5
0

If your flow always follows A => B => C => D => A, you only have to avoid saving B and C in the back stack. This way, when you go back from D, the only available Activity is A.

Code to start Activity B & C:

Intent i = new Intent(...);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // <= Don't save in back stack
startActivity(i);

Code to start Activity A & D:

Intent i = new Intent(...);
startActivity(i);
JonZarate
  • 841
  • 6
  • 28