Writing an application with a good understanding of the activity life cycle is critical to ensure that our application provides a seamless user experience and properly manages its resources.
Android application does not control its own process lifetimes. The Android run time manages the process of each application. While the run time handles the termination and management of an activity's process, the activity's state helps determine the priority of its parent application. The application priority, in turn, affects the likelihood that the run time will terminate it and the activities running within it.
Activity Stacks
The state of each activity is determined by its position on the activity stack. When a new activity starts, the current foreground screen is moved to the top of the stack. If the user navigates back using the Back button or the foreground activity is closed, the next activity on the stack moves up and becomes active.
An application's priority is influenced by its highest-priority activity. When the Android memory manager is deciding which application to terminate to free resources, it uses this stack to determine the priority of applications based on their activities.
Activity States
As activities are created and destroyed they move in and out of the stack. They transition through 4 states:
- Active
When an activity is at the top of the stack it is the visible, focused, foreground activity that is receiving user input. Android will attempt to keep it alive at all cost, killing activities further down the stack as needed, to ensure that it has the resources it needs. When another activity becomes active, this one will be paused. - Paused
In some cases our activity will be visible but will not have focus. At this point it's paused. This state is reached if a transparent or not-full-screen activity is active in front of it. When paused, an activity is treated as if it were active. However, it doesn't receive user input events. In extreme cases, Android will kill a paused activity to recover resources for the active activity. When an activity becomes totally obscured, it is stopped. - Stopped
When an activity isn't visible, it stops. The activity will remain in memory, retaining all state information. However, it is now a candidate for termination when the system requires memory elsewhere. When an activity stopped, it's important to save data and the current UI state. Once an activity exited or closed, it becomes inactive. - Inactive
After an activity has been killed, and before it's been launched, it's inactive. Inactive activities have been removed from the activity stack and need to be restarted before they can be displayed and used.
State transitions are nondeterministic and are handled entirely by the Android memory manager. Android will start by closing applications that contain inactive activities, followed by those that are stopped. In extreme cases it will remove those that are paused.