在Android中,我有一些活动,比如A B C。

在A中,我用下面的代码打开B:

Intent intent = new Intent(this, B.class);
startActivity(intent);

在B中,我用下面的代码打开C:

Intent intent = new Intent(this, C.class);
startActivity(intent);

当用户点击C中的一个按钮时,我想回到a并清除back堆栈(关闭B和C)。所以当用户使用后退按钮B和C不会出现时,我一直在尝试以下方法:

Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(intent);

但是当我回到活动a时,如果我使用后退按钮,B和C仍然会显示出来。我该如何避免这种情况?


当前回答

将android:launchMode="singleTop"添加到activity A的manifest中的activity元素中 然后使用intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)和 当启动活动A时,intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

这意味着当活动A启动时,它上面的所有任务都被清除,这样活动A就在上面。以A为根创建一个新的后台堆栈,并且使用singleTop确保您只启动A一次(因为A现在由于…_CLEAR_TOP而位于顶部)。

其他回答

这个问题困扰了我很长一段时间。最后我是这样解决的:

在片段中,使用:

Intent intent = new Intent(view.getContext(), A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);

在Activity中,使用(再添加一个intent标志intent。FLAG_ACTIVITY_CLEAR_TASK相对于fragment):

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

您可以使用这个示例从活动C调用活动A

Intent loout = new Intent(context, LoginActivity.class); loout.setFlags(意图。| Intent.FLAG_ACTIVITY_CLEAR_TASK; context.startActivity (loout);

高级、可重用的Kotlin:

您可以直接使用setter方法设置标志。在Kotlin或是取代Java位或|。

intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

如果多次使用,创建一个Intent扩展函数

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

你可以在启动intent之前直接调用这个函数

intent.clearStack()

如果您需要在其他情况下添加额外标志的选项,请向扩展函数添加可选参数。

fun Intent.clearStack(additionalFlags: Int = 0) {
    flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

对于未来的研究,请尝试此代码。

Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

从API 16 (Jelly Bean)开始,你可以调用finishAffinity()。

现在你也可以调用ActivityCompat。finishAffinity(活动活动)与兼容性库。

确保将清单中的taskAffinity设置为该组活动唯一的包名。

查看更多信息: http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#finishAffinity%28android.app.Activity%29