Reputation: 3523
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
My concern to do this, when my activity C started, and I press back, app should be exit. Currently its showing me Activity A.
Upvotes: 2
Views: 4543
Reputation: 1260
Add this flag before starting your new activity
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
This will clear the Activity from top of the stack
Upvotes: 0
Reputation: 95578
You can't do it this way. You need to finish()
A when starting C. My favorite way of doing this is as follows:
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);
This will clear the entire task stack (ie: finish activity B and A) and create a new instance of activity A.
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...
}
What you are doing is using your root activity, A, as a kind of "dispatcher".
Upvotes: 5
Reputation: 4382
Try this,
Intent i = new Intent(activityContext, ActivityName.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Upvotes: 0
Reputation: 2511
You can add flag Intent.FLAG_ACTIVITY_CLEAR_TOP
in intent to remove top activity.
Example code is given below.
Intent intent = new Intent(getApplicationContext(), Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Upvotes: 1
Reputation: 4348
please add intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
to remove your stack history also.
Upvotes: 0