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


当前回答

将android:launchMode="singleTop"添加到activity A的manifest中的activity元素中 然后使用intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)和 当启动活动A时,intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

这意味着当活动A启动时,它上面的所有任务都被清除,这样活动A就在上面。以A为根创建一个新的后台堆栈,并且使用singleTop确保您只启动A一次(因为A现在由于…_CLEAR_TOP而位于顶部)。

其他回答

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


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

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

这为我的onBackPressed工作:

public void onBackPressed()
{
    Intent intent = new Intent(ImageUploadActivity.this, InputDataActivity.class);

    Intent myIntent = new Intent(this, ImageUploadActivity.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | 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();

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

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

试着用

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

而不是

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);