The following is the first few sections of a chapter from The Busy Coder's Guide to Android Development, plus headings for the remaining major sections, to give you an idea about the content of the chapter.


Activities and Their Lifecycles

An Android application will have multiple discrete UI facets. For example, a calendar application needs to allow the user to view the calendar, view details of a single event, edit an event (including adding a new one), and so forth. And on smaller-screen devices, like most phones, you may not have room to squeeze all of this on the screen at once.

To handle this, you can have multiple activities. Your calendar application may have one activity to display the calendar, another to add or edit an event, one to provide settings for how the calendar should work, another for your online help, etc. Some of these activities might be private to your app, while others might be able to be launched by third parties, such as your “launcher” activity being available to home screens.

All of this implies that one of your activities has the means to start up another activity. For example, if somebody clicks on an event from the view-calendar activity, you might want to show the view-event activity for that event. This means that, somehow, you need to be able to cause the view-event activity to launch and show a specific event (the one the user clicked upon).

This can be further broken down into two scenarios:

This chapter will cover both of those scenarios.

In addition, frequently it will be important for you to understand when activities are coming and going from the foreground, so you can automatically save or refresh data, etc. This is the so-called “activity lifecycle”, and we will examine it in detail as well in this chapter.

Creating Your Second (and Third and…) Activity

Unfortunately, activities do not create themselves. On the positive side, this does help keep Android developers gainfully employed.

Hence, given a project with one activity, if you want a second activity, you will need to add it yourself. The same holds true for the third activity, the fourth activity, and so on.

The sample we will examine in this section is Activities/Explicit. Our first activity, ExplicitIntentsDemoActivity, started off as just the default activity code generated by the build tools. Now, though, its layout contains a Button:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

  <Button
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="20sp"
    android:text="@string/hello"
    android:onClick="showOther"/>

</LinearLayout>

That Button is tied to a showOther() method in our activity implementation, which we will examine shortly.

Defining the Class and Resources

To create your second (or third or whatever) activity, you first need to create the Java class. You need to create a new Java source file, containing a public Java class that extends Activity directly or indirectly. You have two basic ways of doing this:

To use the Android Studio new-activity wizard, right-click on your app/src/main/ sourceset directory in the project explorer, and go into the New > Activity portion of the context menu. This will give you a submenu of available activity templates — mostly the same roster of templates that we saw back when we created the project in the first place.

If you choose one of those templates, you will be presented with a one-page wizard in which to provide the details for this activity:

Android Studio New-Activity Wizard, Showing Empty Activity Template
Figure 252: Android Studio New-Activity Wizard, Showing Empty Activity Template

What you see here will be based upon the template you chose (e.g., activity name, layout XML resource name) and will resemble those we saw back in the new-project wizard.

Clicking “Finish” will then create the activity’s Java class, related resources (if any), and manifest entry.

Populating the Class and Resources

Once you have your stub activity set up, you can then add an onCreate() method to it (or edit an existing one created by the wizard), filling in all the details (e.g., setContentView()), just like you did with your first activity. Your new activity may need a new layout XML resource or other resources, which you would also have to create (or edit those created for you by the wizard).

In Activities/Explicit, our second activity is OtherActivity, with pretty much the standard bare-bones implementation:

package com.commonsware.android.exint;

import android.app.Activity;
import android.os.Bundle;

public class OtherActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.other);
  }
}

and a similarly simple layout, res/layout/other.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

  <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/other"
    android:textColor="#FFFF0000"
    android:textSize="20sp"/>

</LinearLayout>

Augmenting the Manifest

Simply having an activity implementation is not enough. We also need to add it to our AndroidManifest.xml file. This is automatically handled for you by the IDEs’ respective new-activity wizards. However, if you created the activity “by hand”, you will need to add its manifest element, and over time you will need to edit this element in many cases.

Adding an activity to the manifest is a matter of adding another <activity> element to the <application> element:

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

  <uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="11"/>

  <supports-screens
    android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"/>

  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">
    <activity
      android:name="ExplicitIntentsDemoActivity"
      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="OtherActivity"/>
  </application>

</manifest>

You need the android:name attribute at minimum. Note that we do not include an <intent-filter> child element, as we did with the original activity has. For now, take it on faith that the original activity’s <intent-filter> is what causes it to appear as a launchable activity in the home screen’s launcher. We will get into more details of how that <intent-filter> works and when you might want your own in a later chapter.

Warning! Contains Explicit Intents!

An Intent encapsulates a request, made to Android, for some activity or other receiver to do something.

If the activity you intend to launch is one of your own, you may find it simplest to create an explicit Intent, naming the component you wish to launch. For example, from within your activity, you could create an Intent like this:

new Intent(this, HelpActivity.class);

This would stipulate that you wanted to launch the HelpActivity. HelpActivity would need to have a corresponding <activity> element in your AndroidManifest.xml file.

In Activities/Explicit, ExplicitIntentsDemoActivity has a showOther() method tied to its Button widget’s onClick attribute. That method will use startActivity() with an explicit Intent, identifying OtherActivity:

package com.commonsware.android.exint;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class ExplicitIntentsDemoActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
  
  public void showOther(View v) {
    startActivity(new Intent(this, OtherActivity.class));
  }
}

Our launched activity shows the button:

The Explicit Intents Demo, As Launched
Figure 253: The Explicit Intents Demo, As Launched

Clicking the button brings up the other activity:

The Explicit Intents Demo, After Clicking the Button
Figure 254: The Explicit Intents Demo, After Clicking the Button

Clicking BACK would return us to the first activity. In this respect, the BACK button in Android works much like the BACK button in your Web browser.

Using Implicit Intents

The preview of this section is [REDACTED].

Extra! Extra!

The preview of this section was whisked away by a shark-infested tornado.

Pondering Parcelable

The preview of this section took that left turn at Albuquerque.

Asynchronicity and Results

The preview of this section is sleeping in.

Schroedinger’s Activity

The preview of this section is being chased by zombies.

Life, Death, and Your Activity

The preview of this section was fed to a gremlin, after midnight.

When Activities Die

The preview of this section is in the process of being translated from its native Klingon.

Walking Through the Lifecycle

The preview of this section is [REDACTED].

Recycling Activities

The preview of this section is unavailable right now, but if you leave your name and number at the sound of the tone, it might get back to you (BEEEEEEEEEEEEP!).

Application: Transcending the Activity

The preview of this section is presently indisposed.

The Case of the Invisible Activity

The preview of this section was the victim of a MITM ('Martian in the middle') attack.