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

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

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

这段代码为我在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 intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();