Search code examples
androidback

StartActivity and Multiple Instances


I'm a little puzzled by how activities work. If I do a StartActivity() by pressing a button, and then I press the Back button to get back to the original activity, and then I press the button again to do the same StartActivity(), are there two instances of the new activity? I know onCreate() is called each time, so is the first instance orphaned (presumably eventually Garbage Collected)?

Should I always ensure that finish() is called (via the Back button), just to be safe? I'm not sure what the protocol is here.


Solution

  • From the Android development site (source):

    An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" queue mechanism, so, when the user is done with the current activity and presses the BACK key, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the Tasks and Back Stack document.)

    (bolding by me)

    And this page is especially interesting to understand the way it works in details:

    Tasks and back stack