本文翻译自:Android: Clear the back stack
In Android I have some activities, let's say A, B, C. 在Android中我有一些活动,比方说A,B,C。
In A, I use this code to open B: 在A中,我使用此代码打开B:
Intent intent = new Intent(this, B.class);
startActivity(intent);
In B, I use this code to open C: 在B中,我使用此代码打开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). 当用户点击C中的按钮时,我想返回A并清除后栈(关闭B和C)。 So when the user use the back button B and C will not show up, I've been trying the following: 因此,当用户使用后退按钮B和C不会出现时,我一直在尝试以下方法:
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? 但是当我回到活动A时,如果我使用后退按钮,B和C仍然会出现。我怎么能避免这种情况?
#1楼
参考:https://stackoom.com/question/OJPm/Android-清除后台堆栈
#2楼
As per Wakka in Removing an activity from the history stack ... 根据Wakka 从历史堆栈中删除活动 ...
Add android:noHistory="true"
attribute to your <activity>
in the AndroidManifest.xml
like this: 将android:noHistory="true"
属性添加到AndroidManifest.xml
中的<activity>
,如下所示:
<activity android:name=".MyActivity"
android:noHistory="true">
</activity>
#3楼
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
#4楼
The given code works correctly. 给定的代码正常工作。 I have tried in the Application Life Cycle sample. 我已尝试过Application Life Cycle样本。
I haven't got B and C in the back stack after starting activity A with flag, FLAG_ACTIVITY_CLEAR_TOP 在使用flag,FLAG_ACTIVITY_CLEAR_TOP启动活动A之后,我没有在后台堆栈中获得B和C.
#5楼
Try using 尝试使用
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
and not 并不是
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
#6楼
Starting in API 16 (Jelly Bean), you can just call finishAffinity()
. 从API 16(Jelly Bean)开始,您可以调用finishAffinity()
。
Now you can also call ActivityCompat.finishAffinity(Activity activity)
with the compatibility library. 现在,您还可以使用兼容性库调用ActivityCompat.finishAffinity(Activity activity)
。
Be sure to set taskAffinity in the manifest to a package name unique to that group of activities. 确保将清单中的taskAffinity设置为该组活动所特有的包名称。
See for more info: 查看更多信息:
http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#finishAffinity%28android.app.Activity%29 http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#finishAffinity%28android.app.Activity%29