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)
I want this stack: C | B | A
What's happening?
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:
startactivity(intent) after setting flags, it just finishes E, but not D.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
singleTaskworked?
It created the stack like I wanted [ A | B | C | D | E ] and CLEAR_TOP worked as expected. Done!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With