Android:清除后台堆栈

本文探讨了如何在Android应用中,当用户从C活动返回A活动时,清除后退堆栈,防止B和C活动再次显示。通过设置FLAG_ACTIVITY_CLEAR_TOP标志,或者在API 16及更高版本中使用ActivityCompat.finishAffinity()来实现这一目标。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值