Android Tutorial: The Activity Lifecycle

In this tutorial, we see about The Activity Lifecycle. The first application component that you need to get familiar with is the activity. An activity is a window containing user interface (UI) components that the user can interact with. Starting an activity often means displaying a window.

An activity is an instance of the android.app.Activity class. A typical Android application starts by starting an activity, which, as I said, loosely means showing a window. The first window that the application creates is called the main activity and serves as the entry point to the application. Needless to say, an Android application may contain multiple activities and you specify the main activity by declaring it in the application manifest file.

For example, the following application element in an Android manifest defines two activities, one of which is declared as the main activity using the intent-filter element. To make activity the main activity of an application, its intent-filter element must contain the MAIN action and LAUNCHER category like so.

<application ... >
    <activity 
            android:name="com.example.MainActivity" 
            android:label="@string/app_name" > 
        <intent-filter> 
            <action android:name="android.intent.action.MAIN"/> 
            <category 
                android:name="android.intent.category.LAUNCHER"/> 
        </intent-filter> 
    </activity>
    <activity
            android:name="com.example.SecondActivity"
            android:label="@string/title_activity_second" >
    </activity>
</application>


In the snippet above, it is not hard to see that the first activity is the main activity.

When the user selects an application icon from the Home screen, the system will look for the main activity of the application and start it. Starting an activity entails instantiating the activity class (which is specified in the android:name attribute of the activity element in the manifest) and calling its lifecycle methods. It is important that you understand these methods so you can write code correctly.

Activity Lifecycle

The following are the lifecycle methods of Activity. Some are called once during the application lifetime, some can be called more than once.

  • onCreate
  • onStart
  • onResume
  • onPause
  • onStop
  • onRestart
  • onDestroy

To truly understand how these lifecycle methods come into play, consider the diagram in Figure 1.1.

Figure 1.1: The activity lifecycle

The system begins by calling the onCreate method to create the activity. You should place the code that constructs the UI here. Once onCreate is completed, your activity is said to be in the Created state. This method will only be called once during the activity lifetime.

Next, the system calls the activity’s onStart method. When this method is called, the activity becomes visible. Once this method is completed, the activity is in the Started state. This method may be called more than once during the activity lifetime.

onStart is followed by onResume and once onResume is completed, the activity is in the Resumed state. How I wish they had called it Running instead of Resumed because the fact is this is the state where your activity is fully running. onResume may be called multiple times during the activity lifetime.

Therefore, onCreated, onStart, and onResume will be called successively unless something goes awry during the process. Once in the Resumed state, the activity is basically running and will stay in this state until something occurs to change that, such as if the alarm clock sets off or the screen turns off because the device is going to sleep, or perhaps because another activity is started.

The activity that is leaving the Resumed state will have its onPause method called. Once onPause is completed, the activity enters the Paused state. onPause can be called multiple times during the activity lifetime.

What happens after onPause depends on whether or not your activity becomes completely invisible. If it does, the onStop method is called and the activity enters the Stopped state. On the other hand, if the activity becomes active again after onPause, the system calls the onResume method and the activity re-enters the Resumed state.

Activity in the Stopped state may be re-activated if the user chooses to go back to the activity or for some other reason it goes back to the foreground. In this case, the onRestart method will be called, followed by onStart.

Finally, when the activity is decommissioned, its onDestroy method is called. This method, like onCreate, can only be called once during the activity lifetime.

ActivityDemo Example

The ActivityDemo application accompanying this book demonstrates when the activity lifecycle methods are called. Listing 1.1 shows the manifest for this application.

Listing 1.1: The manifest for ActivityDemo

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.activitydemo" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
        android:minSdkVersion="8" 
        android:targetSdkVersion="21" /> 

    <application 
        android:allowBackup="true" 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" 
        android:theme="@style/AppTheme" > 
        <activity 
            android:name="com.example.activitydemo.MainActivity" 
            android:screenOrientation="landscape" 
            android:label="@string/app_name" > 
            <intent-filter> 
                <action android:name="android.intent.action.MAIN" /> 
                <category 
                    android:name="android.intent.category.LAUNCHER" /> 
            </intent-filter> 
        </activity> 
    </application> 

</manifest>

This manifest is like the one in the previous article Android Tutorial: Environment Setup. It has one activity, the main activity. However, notice that I specify the orientation of the activity using the android:screenOrientation attribute of the activity element.

The main class for this application is printed in Listing 1.2. The class overrides all the lifecycle methods of Activity and prints a debug message in each lifecycle method.

Listing 1.2: The MainActivity class for ActivityDemo

package com.example.activitydemo;
import android.os.Bundle;
import android.app.Activity; 
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        Log.d("lifecycle", "onCreate"); 
        setContentView(R.layout.activity_main); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
        // Inflate the menu; this adds items to the action bar 
        // if it is present. 
        getMenuInflater().inflate(R.menu.menu_main, menu); 
        return true; 
    } 
    
    @Override 
    public void onStart() { 
        super.onStart(); 
        Log.d("lifecycle", "onStart"); 
    } 
    
    @Override 
    public void onRestart() { 
        super.onRestart(); 
        Log.d("lifecycle", "onRestart");        
    } 

    @Override 
    public void onResume() { 
        super.onResume(); 
        Log.d("lifecycle", "onResume");        
    } 

    @Override 
    public void onPause() { 
        super.onPause(); 
        Log.d("lifecycle", "onPause");        
    } 

    @Override 
    public void onStop() { 
        super.onStop(); 
        Log.d("lifecycle", "onStop");        
    } 

    @Override 
    public void onDestroy() { 
        super.onDestroy(); 
        Log.d("lifecycle", "onDestroy"); 
    } 
}


Note that if you override an activity’s lifecycle method, you must call the overridden method in the parent class.

Before you run this application, create a Logcat message filter to show only messages from the application, filtering out system messages, by following these steps.

Select Debug from the Log level drop-down list.

Type in the filter text, in this case “lifecycle,” in the search box. Figure 1.2 shows the Logcat window.

Figure 1.2: Creating a Logcat message filter

Run the application and notice the orientation of the application. It should be landscape. Now, try running another application and then switch back to the ActivityDemo application. Check the messages printed in Logcat.

Note that when you create a new application using Android Studio, the activity class may not extend Activity but ActionBarActivity. ActionBarActivity is a class in the Support Library that supports using the action bar in pre-3.0 Android devices. (The action bar is discussed in the next article) If you are not using the action bar or do not plan on deploying to pre-3.0 Android devices, you can replace ActionBarActivity with Activity.

Changing the Application Icon

If you do not like the application icon you have chosen, you can easily change it by following these steps.

  • Save a jpeg or png file in res/drawable. png is preferred because the format supports transparency.
  • Edit the android:icon attribute of the manifest to point to the new image. You can refer to the image file with this format: @drawable/fileName, where fileName is the name of the image file without the extension.

Using Android Resources

Android is rich, it comes with a bunch of assets (resources) you can use in your apps. To browse the available resources, open the application manifest in Android Studio and fill a property value by typing “@android:followed by Ctrl+space. Android Studio will show the list of assets. (See Figure 1.3).

Figure 1.3: Using Android assets

For example, to see what images/icons are available, select @android:drawable/. To use a different icon for an application, change the value of the android:icon attribute.

android:icon="@android:drawable/ic_menu_day"


Enjoy…

Comments

Android Tutorial: Fragments - Digital Juices

[…] This chapter explains what fragments are and shows how to use them. Related: Android Tutorial: The Activity Lifecycle […]

Android Tutorial: Activity Related Intents - Digital Juices

[…] In the article Activity Related Intents, you learned that you can start a new activity by passing an intent to the startActivity method. You can also call startActivityForResult if you want a result from the invoked activity. Related article: Android Tutorial: The Activity Lifecycle […]

Leave a Reply

Your email address will not be published.