Search code examples
androidandroid-activity

Android - Keep bunch of activities in each task


I have few activities.For example A,B,C,D,E,F.
My Home screen is activity A.Now I start Activity B from that and C from Activity B.

  • So now my stack is A->B->C.
    Now if I press back I should be able to navigate in reverse Order.

    But If I start Activity D from C.
  • I want my stack to be A->D as I want to kill B and C.


My expectations is A is my Home screen which should be always there.B and C on having one task and D,E,F having other task.


There is one more catch - I can even start activity D->E->F from A and B from F. In that case when I start B from F, D,E,F should be removed from stack


Solution

  • There are several ways to accomplish this, depending on your application requireents. You should look at using startActivityForResult() in order to start one (or more) activities which can then return a result to the Activity that launched it. This may be a good solution for you.

    The other alternative is to use your ActivityA as a kind of "dispatcher. In this case, when C wants to launch D but also clear the task stack back to A first, you can do something like this in C:

    Intent intent = new Intent(this, ActivityA.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("launchActivity", "ActivityD");
    

    Using the flags CLEAR_TOP and SINGLE_TOP will cause all activities on top of the existing instance of ActivityA to be finished and cause the Intent to be routed to onNewIntent() of the existing instance of ActivityA.

    Now, in ActivityA, override onNewIntent() with something like this:

    if (intent.hasExtra("launchActivity)) {
        if (intent.getExtra("launchActivity").equals("ActivityD")) {
            Intent launchIntent = new Intent(this, ActivityD.class);
            startActivity(launchIntent);
        } else ...
    }