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


当前回答

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


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

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

其他回答

为我添加意图。FLAG_ACTIVITY_CLEAR_TASK解决了这个问题

Intent i = new Intent(SettingsActivity.this, StartPage.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP  | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
finish();

使用setFlags()方法清除背面打开的所有活动关闭并启动youractivity

Intent intent = new Intent(getApplicationContext(), yourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

高级、可重用的Kotlin:

您可以直接使用setter方法设置标志。在Kotlin或是取代Java位或|。

intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

如果多次使用,创建一个Intent扩展函数

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

你可以在启动intent之前直接调用这个函数

intent.clearStack()

如果您需要在其他情况下添加额外标志的选项,请向扩展函数添加可选参数。

fun Intent.clearStack(additionalFlags: Int = 0) {
    flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

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

android:noHistory="true"

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

@Override
public void onBackPressed() {
   return;
}

将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而位于顶部)。