In Android I have some activities, let's say A, B, C.
In A I use this code to open B:
Intent intent = new Intent(this, B.class);
startActivity(intent);
In B I use this code to open C:
Intent intent = new Intent(this, C.class);
startActivity(intent);
When the user taps a button in C I want to go back to A and clear the back stack (close both B and C). So when the user use the back button B and C will not show up, I've been trying the following:
Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
But B and C are still showing up if I use the back button when I'm back in activity A. How can I avoid this?
Use setFlags() method for clear back side opened all activity close and start yourActvity
This is a really old answer and i didn't really found a proper solution to it, to the sole purpose of clearing the backStack, i decided to create my own backstack, which is not even a stack tbh, but it doesn't have to be, since we want to clear everything in it anyways;
Theres an overhead of handlind the backstack everytime, but it gave me the control i needed;
First Declare a public static List of Activities (or fragments, whatever you need);
And inside all other activity's onCreate method:
And finally, when you want to clear the backstack, simply call:
I found the answers here a little misleading because the code in the original question seems to work fine for me?
With A being the root activity, starting it from B or C only with FLAG_ACTIVITY_CLEAR_TOP does remove B and C from the back stack.
What about adding in manifests file for related activity :
to the activity definition of B and C ? They will not be added to the backstack. Not sure if that is what you want.
You can use this example to call your
Activity A
fromActivity C
Intent loout = new Intent(context, LoginActivity.class); loout.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(loout);
logout.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); logout.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);