2

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?

FlashAsh80
  • 1,357
  • 1
  • 16
  • 27

4 Answers4

3

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);
Some Noob Student
  • 14,186
  • 13
  • 65
  • 103
2

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

sha
  • 1,410
  • 2
  • 18
  • 37
  • I imagine this would would work, but sounds a bit "hacky" was wondering if there was some config I can use with the intent flags. – FlashAsh80 Nov 02 '15 at 22:48
  • As far as I remember, i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); only works if you launch the 1st activity again after 3rd activity which clears all the middle activities and may call onNewIntent(). I use the Broadast receiver approach for implementing 'Logout' which works perfectly. – sha Nov 02 '15 at 22:57
1

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);
SuperFrog
  • 7,631
  • 9
  • 51
  • 81
0

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.

FlashAsh80
  • 1,357
  • 1
  • 16
  • 27