FLAG_ACTIVITY_CLEAR_TOP does not work as expected

I have 4 activities A, B, C, D, E with each declared as android:launchMode="singleInstance" and A being parentActivity of B, and B being parent Activity of C, in manifest.

Now user navigated to E like this: A > B > C > D > E. And I have a button in E with the following onClickListener

    Intent intent = new Intent(E.this, C.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

What I need? (Also according to documentation, if I understood it right, this should happen)

What's happening?

PS: My question is very similar to this however, the answers given there does not suit this question. Some answers I found there and elsewhere:

  1. I can't use NEW_TASK flag, as I need to keep A, B in stack alive.
  2. I can't use startActivityForResult() on D and then finish() it which in fact is a hack, as I have other decisive factors in E such as delivering the intent to some other activity depending on user input.
  3. I can't finish() activity D, while delivering intent to E, and then finish() E while hitting C, which would actually solve the problem. But, if back is pressed on E, i want it go back to D and not C.
  4. When I try finish() on E as soon as I do startactivity(intent) after setting flags, it just finishes E, but not D.

Upvotes: 4

Views: 2094

Answers (2)

Artem Mostyaev's comment solves the puzzle! Use singleTask

So what exactly was the mistake?

When singleInstance is used as launchMode, and when an activity is launched, Android makes sure that it is launched in a new task as if NEW_TASK flag is added, with itself being the only activity inside it.

So when user navigated to E, the stack was never like [ A | B | C | D | E ] Instead there were five different tasks like [A] [B] [C] [D] [E].

And when I tried E > C with CLEAR_TOP, it indeed searched for C in its task and tried to clear all activities after C. But C was never there in the task where E resides.

So it tried launching a new activity C, but then as I set launchMode to singleInstance, it had no way other than bringing [C] front while leaving other tasks untouched.

So how singleTask worked?

It created the stack like I wanted [ A | B | C | D | E ] and CLEAR_TOP worked as expected. Done!

Upvotes: 8

Artem Mostyaev
Artem Mostyaev

Reputation: 3908

The problem is in android:launchMode="singleInstance". According to the documentation for singleInstance:

If this activity tries to start a new activity, that new activity will be launched in a separate task.

So, your activity D is launched as the new task, and that's why it is not deleted.

Upvotes: 4

Related Questions