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.

3
  • you want never have Activity B and C in back stack?
    – miljon
    Commented Mar 20, 2017 at 12:17
  • stackoverflow.com/questions/12358485/… Commented Mar 20, 2017 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
    Commented Mar 20, 2017 at 12:21

3 Answers 3

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.

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);
}
1
  • IMO, this approach is not elegant at all.
    – JonZarate
    Commented Mar 20, 2017 at 12:28
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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.