本文翻譯自: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