Search code examples
javaandroid-studioandroid-activity

How to get an activity from background avoiding to open a new instance of it


My app has three fundamental activity. Like on Instagram, I have a bottom menu where I can choose one of this activity.

When the app starts the first activity that appears is the HomeActivity. So the scheme is like this:

Home --> Activity 2 --> Activity 3.

After Activity3 I can choose to go to the Activity2 or to the Home. However, it's important to say that when I start a new activity, the previous one stays in background. For Example: when I start the Activity3, the Activity2 is kept in background.

The problem is that, when I go from Activity3 to Activity2 like that : Home > Activity 2 > Activity 3 > Activity 2 there will be two different instances of the Activity2, one in background and the other running. So the question is:

How can I change my code to make possible that:

If there is no Activity2 in background, the Activity3 starts a new Actvity2 (like It normally does)

If there is an Activity2 in background, the Activity3 takes the Activity2 from background and makes it running (avoiding to open a second instance of the same Activity2)

It's hard but I hope I've explained it myself! Thanks for the answers!


Solution

  • When you launch one Activity from another, just add FLAG_ACTIVITY_REORDER_TO_FRONT, like this:

    Intent intent = new Intent(this, TargetActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
    

    This will bring the target Activity to the front of the task stack (or create a new instance if there is no existing instance in the task stack). The launching Activity remains active in the task stack.

    In this way you can switch back and forth between your 3 activities and they will just be reshuffled in the task stack.