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 09:58

use this code for starting new activity and close or destroy all other acivity stack or back satack...

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
查看更多
一个人的天荒地老
3楼-- · 2018-12-31 09:59

Intent.FLAG_ACTIVITY_CLEAR_TOP will not work in this case. Please use (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)

For more detail please check out this documentation.

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 10:00
  1. Add android:launchMode="singleTop" to the activity element in your manifest for Activity A
  2. Then use intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) and intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) when starting Activity A

This means that when Activity A is launched, all tasks on top of it are cleared so that A is top. A new back stack is created with A at the root, and using singleTop ensures you only ever launch A once (since A is now on top due to ..._CLEAR_TOP).

查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 10:00

Add NO History Flag in the intent.

In activity B, start the activity C as below >>>>>>

Intent intent = new Intent(this, C.class);
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); 
startActivity(intent);
finish();
查看更多
梦寄多情
6楼-- · 2018-12-31 10:00

Either add this to your Activity B and Activity C

android:noHistory="true"

or Override onBackPressed function to avoid back pressing with a return.

@Override
public void onBackPressed() {
   return;
}
查看更多
余生请多指教
7楼-- · 2018-12-31 10:02

If your application has minimum sdk version 16 then you can use finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.

This is work for me In Top Payment screen remove all back-stack activits,

 @Override
public void onBackPressed() {
         finishAffinity();
        startActivity(new Intent(PaymentDoneActivity.this,Home.class));
    } 

http://developer.android.com/reference/android/app/Activity.html#finishAffinity%28%29

查看更多
登录 后发表回答