Android: Clear the back stack

2018-12-31 09:47发布

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?

30条回答
闭嘴吧你
2楼-- · 2018-12-31 10:19

Use setFlags() method for clear back side opened all activity close and start yourActvity

Intent intent = new Intent(getApplicationContext(), yourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
查看更多
伤终究还是伤i
3楼-- · 2018-12-31 10:19

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);

public static ArrayList <Activity> backStack = new ArrayList<>();

And inside all other activity's onCreate method:

MainActivity.backStack.add(this);

And finally, when you want to clear the backstack, simply call:

public static void killBackStack () {
    for (Activity ac : backStack) {
        if (ac != null)
            ac.finish();
    }
}
查看更多
与君花间醉酒
4楼-- · 2018-12-31 10:22

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.

查看更多
君临天下
5楼-- · 2018-12-31 10:24

What about adding in manifests file for related activity :

android:noHistory="true"

to the activity definition of B and C ? They will not be added to the backstack. Not sure if that is what you want.

查看更多
初与友歌
6楼-- · 2018-12-31 10:24

You can use this example to call your Activity A from Activity C

Intent loout = new Intent(context, LoginActivity.class); loout.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(loout);

查看更多
浪荡孟婆
7楼-- · 2018-12-31 10:25

logout.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); logout.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

查看更多
登录 后发表回答