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


当前回答

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

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

其他回答

 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

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

android:noHistory="true"

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

@Override
public void onBackPressed() {
   return;
}

这段代码为我在kotlin工作:

 val intent = Intent(this, MainActivity::class.java)
 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
 startActivity(intent)
 finish()

试着用

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

而不是

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

使用finishAffinity ();在任务C中启动任务A,清除后台活动。