Understanding the Android activity lifecycle

Boemo Mmopelwa Boemo is a software developer who embraces innovative approaches. He likes diving deep into complex concepts in order to learn and write articles that can help the reader understand complex methodologies in a simple and fun way.

LogRocket Galileo logo

Introducing Galileo AI

LogRocket’s Galileo AI watches every session, surfacing impactful user struggle and key behavior patterns.

The Android activity lifecycle provides details on which methods are called when an activity instance changes state during an application’s lifespan. Understanding the Android activity and fragment lifecycle is crucial when handling activity state changes.

Mastering the Android lifecycle will help you handle activity states effectively and prevent your app from behaving abnormally when an activity state change occurs, helping you retain users and reduce frustration with your Android app.

Therefore, this tutorial will teach you all the methods that are invoked when an activity or fragment changes state in an Android app. In addition, you will also learn how to handle activity and fragment state changes appropriately.

Analyzing the Android activity lifecycle

In Android, an activity is a screen that provides a window for the app to display its UI and enables the user to interact with the app. This activity responds to different state changes that are triggered by the user or the system.

For example, an activity state change occurs when the user presses the back button while using an app. This action triggers the system to stop all the operations being carried out by the app when the user presses the back button.

A programmer can use six callbacks to handle these activity state changes. They are as follows:

1. onCreate()

The Android activity lifecycle starts with the onCreate() method. This method is called when the user clicks on your app’s icon, which causes this method to create the activity. This method is required for every activity, as it sets the layout.

The onCreate() method takes in a Bundle as a parameter. This Bundle will be used by the activity to reinstate itself back to the previous state using the data stored in the Bundle , like so:

@Override public void onCreate(Bundle savedInstanceState)

2. onStart()

After views have been initialized and the layout has been set in the onCreate() method, the onStart() method is called. This method makes the activity visible to the user.

This method can also be triggered by the onRestart() method when the user presses on the back button and opens the activity a few seconds later. The onRestart() method is only called if the activity was invisible but not destroyed by the system.

@Override protected void onStart()

3. onResume()

After the activity is visible to the user, the onResume() method is called when the user starts interacting with it. The activity will continue being in this state until the user leaves the activity.

@Override protected void onResume()

4. onPause()

When the user leaves the current activity, the system pauses all operations occurring on the activity and calls the onPause() method. This method is also crucial, because it is used to save the user’s data on the activity as the user moves to another.

Therefore, tasks implemented on this method have to be fast in order to make sure that the app doesn’t lag when transitioning to another activity.

Over 200k developers use LogRocket to create better digital experiences

Learn more →

@Override protected void onPause()

5. onStop()

When the user presses the back button or navigates to another activity, the onStop() method is called since the activity is no longer visible to the user. You can also save the user’s data on this method.

@Override protected void onStop()

6. onDestroy()

This method is called before the system destroys the activity. An activity may be destroyed due to a change in a configuration, such as when the user changes the device orientation and locale.

@Override protected void onDestroy()

Analyzing the fragment lifecycle

A fragment is a subactivity, or a segment of an activity, that has its own layout and lifecycle. Fragments are used to provide multiple screens in an activity.

The fragment starts its lifecycle by attaching to the activity when the onAttach() method is called. After that, the onCreate() method is used by the system to initialize the fragment.

Just like in the activity lifecycle, the OnCreate() method also initializes the fragment in the fragment lifecycle. The only difference is that it doesn’t set the layout, the system calls the onCreateView() to draw the fragment’s UI.

After a fragment has been created successfully it goes through the following stages:

How to handle activity and fragment state changes

The sole purpose of the Android activity lifecycle was to create methods that could handle state changes and prevent the app from crashing. Even though only one method is required ( onCreate() ), it is imperative to handle additional tasks that release resources when the activity is invisible, including other best practices in the onPause() or onStop() methods.

The following tips show the necessary tasks that have to be done in order for the app to transition smoothly.

Saving the user’s progress

Nowadays, users expect that every app will save their data even if they don’t save the data manually. Always save the user’s data on the onPause() method.

You can store the data on a SQL database or cloud storage platforms such as Firebase for real time storage. But for less data, you can use SharedPreferences for storage.

The following code shows you how to store on SharedPreferences in the onPause() method:

@Override protected void onPause() < super.onPause(); SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE); SharedPreferences.Editor myEdit = sharedPreferences.edit(); //use the putString and putInt methods to store the users text. myEdit.putString("model", model.getText().toString()); myEdit.putInt("price", Integer.parseInt(price.getText().toString())); //save the text by invoking the apply() method myEdit.apply(); >

Releasing resources when the app is inactive

Animations have to be stopped and sensors (hardware resources) unregistered when an activity stops in order to save the user’s battery life. If they are not released, memory leakage will occur, which degrades the system’s performance.

protected void onPause()

Tasks and methods implemented on the activity lifecycle callbacks should be quick and accurate when releasing hardware resources and saving your user’s data on the onPause() method.

Ensure that the code is efficient when carrying out tasks because the next activity will only start if the previous activity has done all the tasks on the onPause() method. If the onPause() method takes too long, it will take a longer time for the next activity to take focus.

Conclusion

By reading this article, you have gained knowledge on the Android activity lifecycle and fragment lifecycle and how to handle activity state changes. I hope you found this article useful and can now handle activity state changes appropriately by designing Android applications that can:

Mastering the Android lifecycle is a necessity if you want to build high-quality applications. But mastering the Android lifecycle shouldn’t be the only skill you practice. Learning more about Android conventions and best practices will also help you program methods that are efficient and make the app transition fast and smoothly between the activity states or fragment states.

In case you have any questions or feedback, please let me know in the comment section below and I will be glad to reply.

Get set up with LogRocket's modern error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID
  2. Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: