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


当前回答

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.

其他回答

根据Wakka在从历史堆栈中移除一个活动…


在AndroidManifest.xml中将android:noHistory="true"属性添加到<activity>中,如下所示:

    <activity android:name=".MyActivity"
        android:noHistory="true">
    </activity>

在我看来,你需要使用startActivityForResult()从活动B启动活动C。当您单击活动C中的按钮时,调用setResult(RESULT_OK)和finish(),这样活动C就结束了。在活动B中,你可以让onActivityResult()通过对自身调用finish()来响应,然后你会被带回活动A。

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

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

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

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

意图。FLAG_ACTIVITY_CLEAR_TOP在这种情况下将不起作用。请使用(意图。FLAG_ACTIVITY_NEW_TASK

欲了解更多细节,请查看此文档。

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