简体   繁体   中英

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

ie 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?

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);

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);

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM