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:10

Starting in API 16 (Jelly Bean), you can just call finishAffinity().

Now you can also call ActivityCompat.finishAffinity(Activity activity) with the compatibility library.

Be sure to set taskAffinity in the manifest to a package name unique to that group of activities.

See for more info:
http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#finishAffinity%28android.app.Activity%29

查看更多
ら面具成の殇う
3楼-- · 2018-12-31 10:10

In manifest

android:launchMode="singleTask"

and

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
查看更多
人气声优
4楼-- · 2018-12-31 10:11

Try adding FLAG_ACTIVITY_NEW_TASK as described in the docs for FLAG_ACTIVITY_CLEAR_TOP:

This launch mode can also be used to good effect in conjunction with FLAG_ACTIVITY_NEW_TASK: if used to start the root activity of a task, it will bring any currently running instance of that task to the foreground, and then clear it to its root state. This is especially useful, for example, when launching an activity from the notification manager.

So your code to launch A would be:

Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);
finish(); // call this to finish the current activity
查看更多
冷夜・残月
5楼-- · 2018-12-31 10:12

As per Wakka in Removing an activity from the history stack...


Add android:noHistory="true" attribute to your <activity> in the AndroidManifest.xml like this:

    <activity android:name=".MyActivity"
        android:noHistory="true">
    </activity>
查看更多
人气声优
6楼-- · 2018-12-31 10:13

Try using

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

and not

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 10:13

Use finishAffinity(); in task C when starting task A to clear backstack activities.

查看更多
登录 后发表回答