Android activity and fragment have their own lifecycle. The entire lifecycle contains several callbacks. Understanding their lifecycles and those callbacks helps us write robust code. This article will explains the lifecycles of activity and fragment.
Table of Contents
Activity Lifecycle
Generally speaking, an activity implements a screen. Most apps contain multiple screens, that is to say, an app contain multiple activities. Among the four application components in Android, activity should be the one we use most often.
The Activity class provides several lifecycle callback methods, and the system notifies the state of the activity by calling them. Therefore, we must understand what these lifecycle callbacks mean and when they will be called by the system. Only in this way can we implement robust code.
The figure below shows the lifecycle of an activity.
The figure below shows activity lifecycle states and events.
The following table lists what we should do in each lifecycle callback. For more details, please refer to Activity lifecycle .
Callback | Lifecycle. State | Lifecycle.Event | when is called | what should be done |
---|---|---|---|---|
onCreate() | CREATED | ON_CREATE | When the system creates the activity | onCreate() will only be executed once in the entire lifecycle of the activity. Implement the startup logic code of the activity. For example, bind data to lists, initialize class-scope variables. |
onStart() | STARTED | ON_START | When the activity is visible | Initialize the code to maintain the UI. |
onResume() | RESUMED | ON_RESUME | When the activity enters the foreground | At this point the Activity can interact with the user. Initialize functionality that will be stopped or system resources that will be freed in onPause(). |
onPause() | STARTED | ON_PAUSE | When the activity leaves the foreground | At this point the activity is not in the foreground, but still visible. Stop functions that are no longer needed and release system resources. For example, stop camera preview. |
onStop() | CREATED | ON_STOP | When the activity is no longer visible | Since the activity is invisible, stop functions that are no longer needed, release system resources, and store data in the database. For example, stop animations. |
onDestroy() | DESTROYED | ON_DESTROY | When the activity is about to be destroyed | Frees all resources that have not been freed. |
At first glance, it seems that we can implement the code to maintain the UI in onStart() or onResume(). But they are still slightly different.
In single-window mode, the screen will only display one window, that is, one activity. Most mobile phones are in this mode. So when the activity leaves the foreground, it often means that the current activity is invisible. However, when a semi-translucent activity is displayed, the current activity is not in the foreground, but it is still visible.
In multi-window mode, the screen can display multiple windows at the same time, that is, multiple activities. For example, a screen could display the Google Map app on the left half and the Chrome app on the right half. If the current focus is on the Google Map app, and we switch the focus to the Chrome app, the current activity of the Google Map app is not in the foreground but still visible.
Fragment Lifecycle
Fragments are reusable UI components. An activity can display multiple fragments. Fragment also has its own lifecycle.
The figure below shows the lifecycle of a fragment and the lifecycle of its view.
State transitions have two directions, Upward state transitions and Downward state transitions. They call callbacks and send events in a different order.
The following table lists what we should do in each lifecycle callback. For more details, please refer to Fragment lifecycle .
Callback | Fragment State | Fragment Events | View State | View Events | when is called | what should be done |
---|---|---|---|---|---|---|
onAttach() | When the fragment is added to the FragmentManager and its host activity | |||||
onCreate() | CREATED | ON_CREATE | When the fragment is created and onAttach() has been called | Restore previously saved states from savedInstanceState. | ||
onCreateView() | CREATED | INITIALIZED | When the fragment need to create its view | Inflate or create a fragment view. | ||
onViewCreated() | CREATED | INITIALIZED | When the view of the fragment has been created | Initialize the code to maintain the view and start observing LiveData. | ||
onViewStateRestored() | CREATED | CREATED | ON_CREATE | Before onStart() is called | Restore to the view state. | |
onStart() | STARTED | ON_START | STARTED | ON_START | When fragment is visible | Initialize the code to maintain the UI. |
onResume() | RESUMED | ON_RESUME | RESUMED | ON_RESUME | When the fragment enters the foreground | At this point fragment can interact with user. Initialize functionality that will be stopped or system resources that will be freed in onPause(). |
onPause() | STARTED | ON_PAUSE | STARTED | ON_PAUSE | When the fragment leaves the foreground | At this point the fragment is not in the foreground, but it is still visible. Stop functions that are no longer needed and release system resources. |
onStop() | CREATED | ON_STOP | CREATED | ON_STOP | When fragment is no longer visible | Since the fragment is invisible, stop functions that are no longer needed and release system resources. |
onSaveInstanceState() | CREATED | CREATED | When onStop() is called | Store instance state. | ||
onDestroyView() | CREATED | DESTROYED | ON_DESTROY | When the fragment’s view has been detached from the window | This is the end of the view’s lifecycle. Release all references to the view so that the view can be garbage collected. | |
onDestroy() | DESTROYED | ON_DESTROY | When fragment is removed from FragmentManager, or FragmentManager is destroyed | This is the end of the lifecycle of the fragment. | ||
onDetach() | When a fragment is removed from its host activity | |||||
ViewModel Lifecycle
In MVVM, ViewModel plays an important role. It contains UI state, and activities and fragments also use it to access business logic.
ViewModel’s lifecycle is directly tied to its scope. It will scope to a ViewModelStoreOwner. It will stay in memory until its scope’s ViewModelStoreOwner disappears. This can happen in the following situations:
- Activity: When it finishes.
- Fragment: When it detaches.
- Navigation entry: When it is removed from the back stack.
The figure below shows the relationship diagram of Activity and ViewModel’s lifecycle. This also applies to Fragment and ViewModel relationships.
It’s worth noting that we often request the ViewModel in onCreate(). But onCreate() may be called multiple times due to configuration change (such as rotate screen). The ViewModel is created only the first time it is requested and exists until the activity is destroyed.
When Configuration Change
Some events will trigger configuration change, such as rotate screen, change language, etc. When a configuration change occurs, the activity is destroyed and recreated. For more details, please refer to Configuration change occurs.
When we navigate from an activity to a new activity, and the new activity completely covers the screen, their state changes are as follows.
When Pressing Back
When the activity is in the foreground and the user presses the Back button, the state changes of the activity are as follows. When the activity is destroyed, it is also removed from the back stack.
When Pressing Home
When the activity is in the foreground and the user presses the Home button, the state changes of the activity are as follows. After pressing Home, the app goes to the background. The current activity of the app may be killed by the system due to low memory.
When Low Memory Occurs
The Android system may kill some activities because it needs to free up RAM. The following table shows which activities the system starts with when it needs to kill activities.
Likelihood of being killed | Process state | Final activity state |
---|---|---|
Least | Foreground (having or about to get focus) | Resumed |
Fewer | Visible (no focus) | Started / Paused |
More | Background (invisible) | stopped |
most | Empty | Destroyed |
Conclusion
Many Android components have their own lifecycle. Only by clearly understanding the lifecycle of each component and doing the right thing at the right time we can write a robust app.
References
- Activity lifecycle , Google developers.
- Fragment lifecycle , Google developers.
- ViewModel overview , Google developers.