在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仍然会显示出来。我该如何避免这种情况?


当前回答

尝试在文档中为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.

其他回答

这为我的onBackPressed工作:

public void onBackPressed()
{
    Intent intent = new Intent(ImageUploadActivity.this, InputDataActivity.class);

    Intent myIntent = new Intent(this, ImageUploadActivity.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
   finish();
}
Use finishAffinity() to clear all backstack with existing one.

Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, 

    - Activity B will be finished / removing from stack.
    - Activity A will be finished / removing from stack.
    - Activity C will finished / removing from stack.

使用此代码启动一个新的活动,并关闭或销毁所有其他活动堆栈或回栈。

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

为相关活动添加清单文件怎么样?

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