从堆栈android中删除顶级活动

时间:2013-11-08 11:32:58

标签: 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

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

5 个答案:

答案 0 :(得分: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);

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

现在,在活动A的onCreate()中,执行此操作(在调用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...
}

您正在做的是使用您的根活动A作为一种“调度程序”。

答案 1 :(得分:1)

您可以在意图中添加标记Intent.FLAG_ACTIVITY_CLEAR_TOP以删除热门活动。

示例代码如下。

Intent intent = new Intent(getApplicationContext(), Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

答案 2 :(得分:0)

请添加intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);以删除您的堆叠历史记录。

答案 3 :(得分:0)

试试这个,

Intent i = new Intent(activityContext, ActivityName.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

答案 4 :(得分:0)

在开始新活动之前添加此标志

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)

这将从堆栈顶部清除活动