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.

Understanding the Android activity lifecycle

4 min read 1308

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) {  
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Button btnregister = (Button) findViewById(R.id.btnregister);
}

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.

We made a custom demo for .
No really. Click here to check it out.

@Override
protected void onStart() {
    super.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() {
    super.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.

@Override
protected void onPause() {
    super.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() {
    super.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() {
    super.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:

  • The onStart() method is called when the fragment is now visible to the user followed by the onResume() method, which is called when the fragment is interactive
  • The onPause() method is called once the fragment is no longer interactive. Use this method to clear hardware resources and save the user’s progress
  • The onStop() method is called when the fragment is no longer visible, and is followed by the onDestroy() and onDestroyView() methods, which clean up any resources on the UI that need cleaning
  • The onDetach() method ends the lifecycle of the fragment as the fragment is detached from the activity

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() {
    super.onPause();
    sensorManager.unregisterListener(this);
}

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:

  • Save the user’s data when the activity stops
  • Releasing unused resources before the activity gets destroyed
  • Bind data when the activity gets created

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.

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
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.

Leave a Reply