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.
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:
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); }
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() { super.onStart(); }
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(); }
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(); }
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(); }
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(); }
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:
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 interactiveonPause()
method is called once the fragment is no longer interactive. Use this method to clear hardware resources and save the user’s progressonStop()
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 cleaningonDetach()
method ends the lifecycle of the fragment as the fragment is detached from the activityThe 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.
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(); }
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.
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.
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: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.