3

I have an app with a MainActivity and ChildAaActivity and ChildBbActivity.

MainActivity can send us to either of the Child activities and the user can move between the two Child activities as often as they want.

However, there must only be one instance of each of these activities.

The problem is, if I make the child activities singleInstance, then they are all separate tasks and switching to another app and back to the child means that onBackPress I exit the app (when I should return to MainActivity)

If I leave launchMode as standard, then I get multiple instances of the child activities, especially when moving back and forth between the two children.

If I use singleTop, then I have both problems

If I use noHistory on the children I can't freely move between them (first back press would return me to MainActivity)

Using isTaskRoot() obviously wont work with singleInstance to fix the app exiting bug, because it will always be true (and isn't useful for the other scenarios)

How should I correctly achieve the behaviour I need?

  • Only one instance of each Activity in the back stack
  • All in the same task / don't exit onBackPress after switching apps
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
  • 1
    This is how I would do it: have two Activities, MainActivity and ChildActivity, and ChildActivity would show either FragmentA or FragmentB when started. Then you could easily switch between FragmentA and FragmentB with fragment transactions while staying on ChildActivity, and you can also easily navigate back to MainActivity when needed. – Daniel Nugent Apr 11 '17 at 23:41

1 Answers1

5

You don't need any special launch modes. Whenever you start a child Activity, use the following flag:

intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

This will move an existing instance of the Activity to the front of the task stack (if there is one), or create a new instance (if there isn't an existing instance).

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Thanks, this seems to be the solution. I was considering using flags but I was hoping for an equivalent from the manifest, to avoid it ever being missed in future changes – Nick Cardoso Apr 12 '17 at 13:39
  • No, there's no way to do this from the manifest. It is more of a behavour thing than a configuration thing. Whether or not you want to reuse an existing instance isn't something you can configure. – David Wasser Apr 12 '17 at 14:47