从堆栈的Andr​​oid删除顶部活动堆栈、Andr、oid

2023-09-12 05:41:04 作者:囍你哟

我是活性的,然后我开始b活动从答:现在我是b活动,并在活动开始Ç开始活动C来自B.,我想删除这两个活动A和B. 我想这样一来,

I am on activity A then I start Activity B from A. Now I am on activity B and starting activity C from B. While starting activity C, I want to remove both Activities A and B. I tried this way,

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

我的关注要做到这一点,在我的活动下开始的,我preSS回来了,应用程序应该退出。目前,它向我展示活动一。

My concern to do this, when my activity C started, and I press back, app should be exit. Currently its showing me Activity A.

推荐答案

您不能做这种方式。开始C.我最喜欢做的,这是如下的方式,当你需要完成()答:

You can't do it this way. You need to finish() A when starting C. My favorite way of doing this is as follows:

在B,当你要开始C,做到这一点:

In B, when you want to start C, do it this:

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的新实例

This will clear the entire task stack (ie: finish activity B and A) and create a new instance of activity A.

现在,在的onCreate()活动A的,做到这一点(在调用后 super.onCreate()

Now, in onCreate() of activity A, do this (after calling 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,作为一种调度员。

What you are doing is using your root activity, A, as a kind of "dispatcher".