FLAG_ACTIVITY_CLEAR_TOP does not work as expected

Viewed 1963

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)

  • Activities D and E should be cleared from stack
  • Activity C should be resumed receiving the intent (as singleInstance is set, it will not be created newly)

    I want this stack: C | B | A

What's happening?

  • Activity C is resumed receiving the intent
  • Activities D and E are NOT cleared from stack. I can click back button again and again to see E, D, B, A.

    I get this stack: C | E | D | B | A

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.
2 Answers
Related