如何在启动 Activity 时忽略 "SingleTask" 的启动模式?

How to ignore the launcheMode of "SingleTask" when starting an Activity?

B 的启动模式为 "SingleTask" 的三个 Activity。我想知道在使用 C 时如何启动一个新的 B 而不是重新启动旧的 B?

不幸的是,如果 Activity B 在清单中设置为使用 android:launchMode="singleTask",则无法(据我所知)覆盖它。

但是,当您想要 singleTask 行为时,您可以从清单中删除此属性并改为使用这样的代码:

Intent intent = new Intent(this, ActivityB.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

最终结果是 singleTask 想要的行为得到,不想要的行为得不到。你只需要改变策略。

在activity

的onBack press方法中使用下面的代码
    @Override
    public void onBackPressed() {
    Intent BackpressedIntent = new Intent();
    BackpressedIntent .setClass(getApplicationContext(),B.class);
    BackpressedIntent .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(BackpressedIntent );
    finish();
}