从堆栈android中删除顶级活动

Rah*_*yay 2 android android-activity

我在活动A然后从A开始活动B.现在我在活动B并从B开始活动C.在开始活动C时,我想删除活动A和B.我试过这种方式,

Intent intent = new Intent(B.this, C.class); //I'm on Activity B, moving to C
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //this should remove the Activity A
startActivity(intent);
finish(); //Finishes activity B
Run Code Online (Sandbox Code Playgroud)

我担心这样做,当我的活动C开始时,我按回来,应该退出应用程序.目前它向我展示了活动A.

Dav*_*ser 5

你不能这样做.finish()启动时你需要A.我最喜欢这样做的方法如下:

在B中,当你想要启动C时,请执行以下操作:

Intent intent = new Intent(B.this, A.class); //Return to the root activity: A
intent.putExtra("launchActivityC", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //this will clear the entire task stack and create a new instance of A
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

这将清除整个任务堆栈(即:完成活动B和A)并创建活动A的新实例.

现在,在onCreate()活动A中,执行此操作(调用后super.onCreate()):

if (getIntent().hasExtra("launchActivityC")) {
    // User wants to launch C now and finish A
    Intent intent = new Intent(this, C.class);
    startActivity(intent);
    finish();
    return; // Return immediately so we don't continue with the rest of the onCreate...
}
Run Code Online (Sandbox Code Playgroud)

你正在做的是使用你的根活动,A,作为一种"调度员".