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


当前回答

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

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

其他回答

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

在片段中,使用:

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

在kotlin中,它几乎与java相同。只有|符号被或文本替换。 它的写法是-

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

我是这样解决这个问题的:

private boolean clearHistoryBackStack = true;

@Override
public final void finish() {
    super.finish();

    if(clearHistoryBackStack)
        finishAffinity();
}

或者把这个添加到你的活动B和活动C中

android:noHistory="true"

或覆盖onBackPressed函数以避免返回。

@Override
public void onBackPressed() {
   return;
}