Activity Lifecycle in Android

Activity is represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application.

Android app contain many activity as a stack and represent as per user interaction. But activity have there own callback events. Its called activity lifecycle. See below image from developer site.android-activity-lifecycle-skynils

So far we have use one callback method onCreate() in every activity, but still other methods are available. This all methods are works from start to end of Activity. Its possible you don’t need all methods to use but its important to know about it and understand very well. Let’s see all callback method one by one.

Callback Method Details
onCreate() This is first callback method and called only when the activity is first created. Its called only once.
onStart() This callback method is called after onCreate() and when the activity becomes visible to the user.
onResume() This callback method  is called when the user starts interacting with the application.
onPause() This callback method is called when other activity started over current activity or application goes to background. E.g. when we start new activity our current activity goes to backstack or we press home button and app goes to background at that time onPause() method is called.
onStop() This callback method is called when the activity is finish or no longer visible.
onDestroy() This callback method is called before the activity is destroyed.
onRestart() This callback method is called when the activity restarts after stopping it.

Let’s see simple example of Activity Lifecycle.

activity_main.xml

MianActivity.java

Now run project and see in logcat.

Remark: To see our log go to Android Monitor at bottom of Android Studio. Set Log Level in center top of Android Monitor as per your requirement. Here we have use error log so set error log level.

Open Android Monitor before run project. When app is run our three methods(onCreate(), onStart(), onResume() ) called and when you close app other(onPause(), onStop(), onDestroy() ) where called.

android-activity-lifecycle-output-skynils

Download Project.

downlod