Android Activity Life Cycle

Importance of Activity's Life cycle

Understanding Android Activity Life cycle is one of the most important things for android developers. Using the activity life cycle correctly can avoid your application from:

Losing the user data when the screen orientation changes

Crashing of application while switching between applications

Consuming valuable resources of the phone while the user is not using you app

Losing the users data when user leaves you app and return later Here an important point is, the activity is recreated with the phone's orientation is changes. So to give your users best experience, you need to take care of this too. Activity Life cycle Callbacks To give the users of your application best user experience, it is very important to understand the activity life cycle. To manage you activities, android provides various callbacks on different stages of activity life cycle. They are listed below:

onCreate() onStart() onResume() onPause() onStop() onRestart() onDestroy()

And also see the demo project running given at the end of the tutorial. They all are called on different stages of activity life. To understand which callback is called when, see the table and image from the official documentation of android below carefully.

Android Activity Life Cycle



Method Description onCreate called when activity is first created. You must implement this callback. onStart When the activity enters the Started state, the system invokes this callback. The system prepares to enter the activity to foreground. onResume called when activity will be in visible form to the user. This is the state in which the app interacts with the user. onPause called when activity is not in focus. It is the first indication that the user is leaving the activity. It does not mean that activity is going to destroy. When a new dialog(popup) or multi window in android 7.0 and higher is made, it is also called as the app loses the focus. onStop called when activity is no longer visible to the user. It usually happens when a new activity is launched. onRestart called after your activity is stopped, prior to start. onDestroy called before the activity is destroyed. After that your activity will be removed from the memory.

Save the State of your App To save the state of your application, android provides two callbacks onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) . From these two callbacks, you can save and restore the data and make the user experience better. These callbacks are called when the orientation of the app is changed or app is brought to foreground again. onSaveInstanceState(Bundle savedInstanceState) is called after onPause() and similarly onRestoreInstanceState(Bundle savedInstanceState) is called onStart() method. Demo Project