Android Activity and Fragment Lifecycles

Photo by Sorasak on Unsplash
Photo by Sorasak on Unsplash
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.

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.

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.

A simplified illustration of the activity lifecycle from <a href=
A simplified illustration of the activity lifecycle from Google developers .

The figure below shows activity lifecycle states and events.

States and events that comprise the activity lifecycle from Google developers.
States and events that comprise the activity lifecycle from Google developers .

The following table lists what we should do in each lifecycle callback. For more details, please refer to Activity lifecycle .

CallbackLifecycle. StateLifecycle.Eventwhen is calledwhat should be done
onCreate()CREATEDON_CREATEWhen the system creates the activityonCreate() 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()STARTEDON_STARTWhen the activity is visibleInitialize the code to maintain the UI.
onResume()RESUMEDON_RESUMEWhen the activity enters the foregroundAt 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()STARTEDON_PAUSEWhen the activity leaves the foregroundAt 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()CREATEDON_STOPWhen the activity is no longer visibleSince 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()DESTROYEDON_DESTROYWhen the activity is about to be destroyedFrees 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.

Fragment lifecycle states and callbacks from <a href=
Fragment lifecycle states and callbacks from Google developers .

State transitions have two directions, Upward state transitions and Downward state transitions. They call callbacks and send events in a different order.

Fragment state transitions
Fragment state transitions

The following table lists what we should do in each lifecycle callback. For more details, please refer to Fragment lifecycle .

CallbackFragment StateFragment EventsView StateView Eventswhen is calledwhat should be done
onAttach()When the fragment is added to the FragmentManager and its host activity
onCreate()CREATEDON_CREATEWhen the fragment is created and onAttach() has been calledRestore previously saved states from savedInstanceState.
onCreateView()CREATEDINITIALIZEDWhen the fragment need to create its viewInflate or create a fragment view.
onViewCreated()CREATEDINITIALIZEDWhen the view of the fragment has been createdInitialize the code to maintain the view and start observing LiveData.
onViewStateRestored()CREATEDCREATEDON_CREATEBefore onStart() is calledRestore to the view state.
onStart()STARTEDON_STARTSTARTEDON_STARTWhen fragment is visibleInitialize the code to maintain the UI.
onResume()RESUMEDON_RESUMERESUMEDON_RESUMEWhen the fragment enters the foregroundAt this point fragment can interact with user. Initialize functionality that will be stopped or system resources that will be freed in onPause().
onPause()STARTEDON_PAUSESTARTEDON_PAUSEWhen the fragment leaves the foregroundAt 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()CREATEDON_STOPCREATEDON_STOPWhen fragment is no longer visibleSince the fragment is invisible, stop functions that are no longer needed and release system resources.
onSaveInstanceState()CREATEDCREATEDWhen onStop() is calledStore instance state.
onDestroyView()CREATEDDESTROYEDON_DESTROYWhen the fragment’s view has been detached from the windowThis is the end of the view’s lifecycle. Release all references to the view so that the view can be garbage collected.
onDestroy()DESTROYEDON_DESTROYWhen fragment is removed from FragmentManager, or FragmentManager is destroyedThis 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.

ViewModel lifecycle from <a href=
ViewModel lifecycle from Google developers .

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 a configuration change occurs.
When a configuration change occurs.

When Navigating from an Activity to a New Activity

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 navigate from activity A to activity B, the state changes of A and B.
When navigate from activity A to activity B, the state changes of A and B.

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 click Back, the state changes of the activity.
When click Back, the state changes of the activity.

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 click Home, the state changes of the activity.
When click Home, the state changes of the activity.

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 killedProcess stateFinal activity state
LeastForeground (having or about to get focus)Resumed
FewerVisible (no focus)Started / Paused
MoreBackground (invisible)stopped
mostEmptyDestroyed
Relationship between process lifecycle and activity state from Google developers.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like