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


当前回答

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

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

其他回答

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

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)

为相关活动添加清单文件怎么样?

android:noHistory="true"

B和C的活动定义?它们不会被添加到后台堆栈。不知道这是不是你想要的。

对于未来的研究,请尝试此代码。

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

我尝试了所有的解决方案,但没有一个单独对我有效。 我的解决方案是:

在android manifest中使用[android:launchMode=" SingleTop "]将活动A声明为SingleTop。

现在,在从任何地方启动A时添加以下标志。它将清空堆栈。

Intent in = new Intent(mContext, A.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(in);
finish();

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