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


当前回答

你不会得到任何活动按后退按钮之后:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | 
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finishAffinity();
finish();

其他回答

使用setFlags()方法清除背面打开的所有活动关闭并启动youractivity

Intent intent = new Intent(getApplicationContext(), yourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
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.

我发现这里的答案有点误导,因为原始问题中的代码似乎对我很好?

如果A是根活动,那么只有使用FLAG_ACTIVITY_CLEAR_TOP从B或C启动它才会从后台堆栈中删除B和C。

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


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

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

除了FLAG_ACTIVITY_CLEAR_TOP,你可以尝试添加Intent。FLAG_ACTIVITY_SINGLE_TOP:

intent.addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);