Search code examples
androidandroid-activitystacktaskback

Android push a new activity while clearing others


I have a series of activities A,B,C that upon completion need to push a new activity Y onto my home activity. The task stack should look as follows.

  • H
  • H->A
  • H->A->B
  • H->A->B->C
  • H->Y

I need the back button to be able to get from C back to B or B back to A, but then C is "done" I need to go have Y be the active task. And "back" from Y needs to go back to home (H).

Thanks.


Solution

  • Jamie, doing Android stuff now? What a scary thought! Anyway, finish() is your friend when it comes to removing activities from the stack. You can call it multiple times to pop multiple activities from the stack.

    Alternatively, you can also erase the entire stack by passing the FLAG_ACTIVITY_CLEAR_TOP flag in your intent (but it sounds like you want to keep H, so that may not be a wise choice).

    Btw, one thing I haven't played with is FLAG_ACTIVITY_NEW_TASK, but that might work in your case. Pass it before starting A. This may be completely useless in your case though, so just experiment with it a bit.

    EDIT: Played with it a bit, calling finish() multiple times actually doesn't work as expected. I got it to work by starting H with FLAG_ACTIVITY_CLEAR_TOP, and then Y immediately afterwards (i.e. two startActivity calls in one function).