从堆栈中删除一系列活动

Remove a range of activities from the stack

我有一个 activity A 会转到 B,然后是 C,然后是 D,​​然后是 F,完成 F 后我想再次跳转到 B,但是所有活动 C、D 和 F 都需要从历史记录中删除但仍然可以从 B 返回到 A,我有办法做到这一点吗?谢谢!!

您可以拦截 Activity F(或其他事件)中的后退按钮按下事件,并使用 intent 返回到 activity B。

@override
public void onBackPressed(){
    // Do what you need done here 
    Intent intent = new Intent(this, ActivityB.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // if you need to pass data back to ActivityB
    //intent.putExtra("tagName", yourData);
    startActivity(intent);
    this.finish();
}

按照 xbadal 的建议添加标志是正确的想法,但根据 Android 文档,您似乎需要使用 FLAG_ACTIVITY_CLEAR_TOP.

来自 Android 文档:

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.

https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

根据调用 intent 时设置的其他标志,您可能需要通过调用 getFlags() 并使用 [= 删除冲突的标志来检查已包含哪些标志15=].

试试这个。这将清除您之前的所有堆栈并开始一个新的 activity

 Intent intent= new Intent(F.this, B.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    ActivityCompat.finishAffinity(this)