MobileAndroidLearn the Basics of Android Activity Lifecycle Events

Learn the Basics of Android Activity Lifecycle Events

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

If you have been building Android applications, you have already come across Android “Activities”, either implicitly or explicitly. If you have worked with activities before, this article will serve as a refresher. If not, you will be able to walk away with a basic understanding of activities and learn how to start, pause, resume, and stop activities.

Basics

The official Android documentation shows an Activity as an application component that provides a UI for users to interact with to do something: it could be making a call, taking videos, reading text messages, and so forth. Each activity has a window on which the UI is drawn; whether it is full screen, or only occupies only a portion of the mobile real estate.

Android application consist of multiple activities, one of which is called the “main” activity and is the one that shows up when the application is first launched.

Each activity can launch another activity to perform actions. Upon the start of a new activity, the previous activity stops and information of the previous activity is put on the stack. Any new activity that starts is placed on the stack and becomes the running activity. The previous activity will only come to the foreground again when the running activity exits.

There are four states of activity. They are as follows:

  1. Active/Running: When the activity is in the foreground, it is considered active or running and is on the top of the stack.
  2. Paused: When the activity has lost focus but is still visible, it is considered to be paused. It is alive but in case of extreme low memory situations, the OS can kill it.
  3. Stopped: When the activity is completely obscured by another activity, it is in the stopped state. It retains all state and member information, but is not visible to the user, so its window is hidden. In case of extreme low memory situations, the OS can kill a stopped activity.
  4. Restarted: When an activity that has been paused or stopped and subsequently killed by the OS, and is initiated once again, it is said to be in the restarted state. The OS is responsible for restoring it to its previous state.

Life1
Figure 1: The four states of activity
Source: https://developer.android.com

Good programming practices dictate that you handle the various activity events to ensure that the application handles the following situations gracefully without crashing:

  1. Receiving calls, messages, or notifications while the activity is running.
  2. Handle low memory situations when the operating system can kill unnecessary activities.
  3. Handle orientation changes without losing activity progress.

Hands on

Let’s create a simple Android application that demonstrates working with Activities.

Fire up Android Studio and start a new Android Studio Project.

Life2
Figure 2: Android Studio is opening

Provide ActivityDemo as the Application Name and click Next.

Life3
Figure 3: Starting a new project

On the next screen, leave the default values as is and click Next.

Life4
Figure 4: Leaving the default values in place

On the “Add an activity to Mobile” page, choose “Blank Activity”. This creates an application with a single activity.

Life5
Figure 5: Creating a blank activity

We are then prompted to customize the activity. We will leave the default values unchanged.

Life6
Figure 6: Leaving the default values unchanged

Click Finish to create the project files.

Our application is now created. If you open up AndroidManifest.xml, you will notice the following:

<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/
   apk/res/android"
   package="com.example.vipul.activitydemo">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme">

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name">

         <intent-filter>
             <actionandroid:name="android.intent.
                action.MAIN"/>

            <categoryandroid:name="android.intent.
               category.LAUNCHER"/>
         </intent-filter>
      </activity>
   </application>

</manifest>

In the preceding manifest file, we can see that the MainActivity is listed as the MAIN intent and associated with LAUNCHER. This means that it will be invoked the first time the application is invoked from the App list on the Android device.

Note that if the MAIN or LAUNCHER was not specified, our application will not show up under the home screen.

Open up MainActivity.java and you will notice that there is a default implementation of the onStart event for the activity.

publicclassMainActivityextendsActionBarActivity{

@Override
protectedvoidnCreate(BundlesavedInstanceState){
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   //android.os.Debug.startMethodTracing();

}

We will make one change to add some logging to see the order of events being fired.

publicclassMainActivityextendsActionBarActivity{

@Override
protectedvoidonCreate(BundlesavedInstanceState){
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   //android.os.Debug.startMethodTracing();
   Log.v("Debug","MainActivityOnCreateinvoked");
}

In this method, the default implementation calls the onCreate method of the parent class, and proceeds to set the content view.

We will now similarly add method handlers for the various other events we want to listen to. Note that we add the keyword @Override to indicate that we are overriding the default behavior (parent class).

@Override
protected void onDestroy(){
   super.onDestroy();
   Log.v("Debug","MainActivity onDestroy invoked");
}

@Override
public void onPause(){
   super.onPause();
   Log.v("Debug","MainActivity OnPause invoked");
}

@Override
public void onResume(){
   super.onResume();
   Log.v("Debug","MainActivity onResume invoked");
}

@Override
protected void onStop(){
   super.onStop();
   Log.v("Debug","MainActivity onStop invoked");
}

@Override
protected voidonRestart(){
   super.onRestart();
   Log.v("Debug","MainActivity onRestart invoked");
}

Now, our application is code complete. You can compile and start debugging the application. When the application fires up, switch to the Android logcat window and LogLevel verbose. You will notice the log statements we have put in being outputed whenever there is an activity event.

When the application starts up, we notice the following events.

08-30 20:20:41.605
   2639-2639/com.example.vipul.activitydemo V/Debug
   · MainActivity OnCreate invoked

If you switch to another application on your computer, you will notice other events being logged.

OnPause invoked

08-30 20:21:02.042
   2639-2639/com.example.vipul.activitydemo V/Debug
   · MainActivity onStop invoked

When we restart the application from the AppList, the following events get fired.

08-30 20:21:13.474
   2639-2639/com.example.vipul.activitydemo V/Debug
   · MainActivity onRestart invoked

08-30 20:21:13.582
   2639-2639/com.example.vipul.activitydemo V/Debug
   · MainActivity onResume invoked

If the back button is clicked on the emulator, the following events get invoked.

08-30 20:44:01.960
   2639-2639/com.example.vipul.activitydemo V/Debug
   · MainActivity OnPause invoked

08-30 20:44:05.558
   2639-2639/com.example.vipul.activitydemo V/Debug
   · MainActivity onStop invoked

08-30 20:44:05.559
   2639-2639/com.example.vipul.activitydemo V/Debug
   · MainActivity onDestroy invoked

By looking at the logs, we can see the Android activity lifecycle inaction.

You can download a copy of the source code from the link just below the article.

Summary

In this article, we explored the Android activity lifecycle. I hope you have found this information useful.

About the Author

Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories