FlashAsh80
FlashAsh80

Reputation: 1367

Launch new activity and clear previous activities except home activity

I have a sequence of activity launches below:

Home Activity -> 2nd Activity -> 3rd Activity - > 4th Activity

What I want to achieve is that when the 3rd activity launches the 4th activity, it clears activities 2 and 3 from the backstack. Thus, clicking back on the 4th activity returns to the home activity

i.e. The user should still be able to go back from the 3rd activity to the 2nd, but once the 4th activity is launched, activities 2 and 3 removed.

What's the configuration to achieve this?

Upvotes: 2

Views: 968

Answers (4)

FlashAsh80
FlashAsh80

Reputation: 1367

Although all the answers were useful, and as I only had 2 activities that I wanted to close this is what I did:

  1. startActivityForResult() on Activity 2
  2. On successful launch of Activity 4 on Activity 3 I set RESULT_OK before I call finish() on Activity 3.
  3. On Activity 2, I handle successful result on onActivityResult(), that way I know Activity 4 has been lauched, so I can finish Activity 2.

Therefore both Activity 2 and 3 are closed upon launching of activity 4.

Upvotes: 0

sha
sha

Reputation: 1420

You can register BroadCastReceiver in 2nd and 3rd Activity which has finish() in its onReceive() implementation.

Trigger the broadcast onlaunching 4th Activity.

If its working, move the same Broadcast implementation to BaseClass and add a boolean check to register broadcast or not.

If you are using fragments you can try

getFragmentManager().popBackStack("tag_of_fragment_to_pop", 0);

Upvotes: 2

Some Noob Student
Some Noob Student

Reputation: 14584

Sounds like you want to CLEAR_TOP.

Try this:

Intent i = new Intent(this, HomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

Upvotes: 3

SuperFrog
SuperFrog

Reputation: 7674

I think the easiest way will be to use something as such:

Intent homeActivityIntent = new Intent(fourth.this,
                        home.class);
homeActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
homeActivityIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(homeActivityIntent);

Upvotes: 1

Related Questions