在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:noHistory="true"

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而位于顶部)。

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

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

尝试在文档中为FLAG_ACTIVITY_CLEAR_TOP添加FLAG_ACTIVITY_NEW_TASK:

这种启动模式也可以用于 配合使用效果好 FLAG_ACTIVITY_NEW_TASK:如果使用 启动一个任务的根活动it 会不会带来目前的运行 实例的 前景,然后清除到它的 根的状态。这个特别有用, 例如,当启动 来自通知的活动 经理。

启动A的代码是:

Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);
CurrentActivity.this.finish(); // if the activity running has it's own context


// view.getContext().finish() for fragments etc.

给定的代码可以正常工作。我在应用程序生命周期示例中尝试过。

我没有得到B和C在后面的堆栈开始活动A与标志,FLAG_ACTIVITY_CLEAR_TOP

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

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();