Home > Articles > Programming > Java

Android Application Basics: Activities and Intents

After providing a brief overview of the basic building blocks of an Android application, this chapter explains activities and the intents that launch them.
This chapter is from the book

Each Android application is represented by a single Android project. An overview of the project structure, including a brief introduction to the basic building blocks of an application, is provided as useful background information for the recipes in this book. Then the focus of this chapter turns to activities and the intents that launch them.

Android Application Overview

An Android application consists of various functionalities. Some examples are editing a note, playing a music file, ringing an alarm, or opening a phone contact. These functionalities can be classified into four different Android components, shown in Table 2.1, each of which is specified by a Java base class.

Table 2.1. The Four Possible Components of an Android Application

Functionality

Java Base Class

Examples

Focused thing a user can do

Activity

Edit a note, play a game

Background process

Service

Play music, update weather icon

Receive messages

BroadcastReceiver

Trigger alarm upon event

Store and retrieve data

ContentProvider

Open a phone contact

Every application is made up of one or more of these components. They are instantiated by the Android operating system (OS) as needed. Other applications are allowed to use them, too, within the specified permissions.

As multiple functionalities play out in the OS (some not even related to the intended application, such as an incoming phone call), each component goes through a lifecycle of getting created, focused, defocused, and destroyed. The default behavior can be overridden for a graceful operation, such as saving variables or restoring user interface (UI) elements.

With the exception of ContentProvider, each component is activated by an asynchronous message called an Intent. The Intent can contain a Bundle of supporting information describing the component. This provides a method of passing information between components.

The rest of this chapter demonstrates the previous concepts using the most common component: the Activity. Because activities almost always specify an interaction with a user, a window is automatically created with each activity. Therefore, a short introduction to the UI is also included. Of the other components, Service and BroadcastReceiver are covered in Chapter 3, "Threads, Services, Receivers, and Alerts," and ContentProvider is covered in Chapter 9, "Data Storage Methods."

Recipe: Creating a Project and an Activity

A straightforward way to create an Android project or any of its components is to use the Eclipse Integrated Development Environment (IDE). This method ensures proper setup of the supporting files. The steps to create a new Android project are

  1. In Eclipse, choose File u2192.jpg New u2192.jpg Android Project. This displays a New Android Project creation screen.
  2. Fill in the Project name, such as SimpleActivityExample.
  3. Select a Build Target from the choices provided. These choices are based on the Software Development Kit (SDK) versions that are installed on the development computer.
  4. Fill in the Application name, such as Example of Basic Activity.
  5. Fill in the Package name, such as com.cookbook.simple_activity.
  6. To create the main activity in the same step, be sure Create Activity is checked and fill in an Activity name, such as SimpleActivity.

All activities extend the abstract class Activity or one of its subclasses. The entry point to each activity is the onCreate() method. It is almost always overridden to initialize the activity, such as setting up the UI, creating button listeners, initializing parameters, and starting threads.

If the main activity is not created with the project or another activity needs to be added, the steps to create an activity are

  1. Create a class to extend Activity. (In Eclipse, this can be done by right-clicking on the project, choosing New u2192.jpg Class, and then specifying android.app.Activity as the super class.)
  2. Override the onCreate() function. (In Eclipse, this can be done by right-clicking on the class file, choosing Source u2192.jpg Override/Implement Methods..., and then checking the onCreate() method.)
  3. As with most overridden functions, it must invoke the super class method, too; otherwise, an exception may be thrown at run-time. Here, the super.onCreate() should be called first to properly initialize the activity, as shown in Listing 2.1.

    Listing 2.1. src/com/cookbook/simple_activity/SimpleActivity.java

    package com.cookbook.simple_activity;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    public class SimpleActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    }
    
  4. If a UI is used, specify the layout in an XML file in the res/layout/ directory. Here it is called main.xml, as shown in Listing 2.2.
  5. Set the layout of the activity using the setContentView() function and passing it the resource ID for the XML layout file. Here, it is R.layout.main, as shown in Listing 2.1.

    Listing 2.2. res/layout/main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    </LinearLayout>
    
  6. Declare the properties of the activity in the AndroidManifest XML file. This is covered in more detail in Listing 2.5.

Note that the string resources are defined in the strings.xml file in the res/values/ folder, as shown in Listing 2.3. This provides a central place for all strings in case text needs to be changed or reused.

Listing 2.3. res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, SimpleActivity!</string>
    <string name="app_name">SimpleActivity</string>
</resources>

Now a more detailed look at the directory structure of this project and the additional auto-generated content is explored.

Directory Structure of Project and Autogenerated Content

Figure 2.1 shows an example project structure, as seen from the Eclipse Package Explorer.

Figure 2.1

Figure 2.1 Android project directory structure, as seen in the Eclipse IDE.

With the exception of the Android 2.0 library, the project structure is a mix of user-generated and auto-generated files.

User-generated files include

  • src/ contains the Java packages the developer writes or imports for the application. Each package can have multiple .java files representing different classes.
  • res/layout/ contains the XML files that specify the layout of each screen.
  • res/values/ contains the XML files used as references by other files.
  • res/drawable-hdpi/, res/drawable-mdpi/, and res/drawable-ldpi/ are directories that contain pictures the application uses. They have high, medium, and low dots-per-inch resolution, respectively.
  • assets/ contains additional nonmedia files the application uses.
  • AndroidManifest.xml specifies the project to the Android OS.

Autogenerated files include

  • gen/ contains autogenerated code, including the generated class R.java.
  • default.properties contains project settings. Although autogenerated, it should be kept under revision control.

An application's resources include XML files describing the layout, XML files describing values such as strings, labels of UI elements, and additional supporting files such as pictures and sounds. At compile time, references to the resources are gathered into an autogenerated wrapper class called R.java. The Android Asset Packaging Tool (aapt) autogenerates this file. Listing 2.4 shows what it looks like for the "Creating a Project and an Activity" recipe.

Listing 2.4. gen/com/cookbook/simple_activity/R.java

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.cookbook.simple_activity;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040001;
        public static final int hello=0x7f040000;
    }
}

Here, each resource is mapped to a unique integer value. In this way, the R.java class provides a way to reference external resources within Java code. For example, to reference the main.xml layout file in Java, the R.layout.main integer is used. To reference the same within XML files, the "@layout/main" string is used.

Referencing resources from within Java or XML files is demonstrated in Table 2.2. Note that to define a new button ID called home_button, the plus sign is added to the identifying string: @+id/home_button. More complete details on resources are given in Chapter 4, "User Interface Layout," but this suffices to cover the recipes in this chapter.

Table 2.2. How Different Resources Are Referenced from Within Java and XML Files

Resource

Reference in Java

Reference in XML

res/layout/main.xml

R.layout.main

@layout/main

res/drawable-hdpi/icon.png

R.drawable.icon

@drawable/icon

@+id/home_button

R.id.home_button

@id/home_button

<string name="hello">

R.string.hello

@string/hello

Android Package and Manifest File

The Android project, sometimes also referred to as an Android package, is a collection of Java packages. Different Android packages can have the same Java package names, whereas the Android package name must be unique across all applications installed on the Android device.

For the OS to access them, each application must declare its available components in a single AndroidManifest XML file. In addition, this file contains the required permissions and behavior for the application to run. Listing 2.5 shows what it looks like for the "Creating a Project and an Activity" recipe.

Listing 2.5. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.cookbook.simple_activity"
          android:versionCode="1"
          android:versionName="1.0">
    <application android:icon="@drawable/icon"
                 android:label="@string/app_name">
        <activity android:name=".SimpleActivity"
                  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>
    <uses-sdk android:minSdkVersion="3" />
</manifest>

The first line is required and standard across all XML files in Android to specify the encoding. The manifest element defines the Android package name and version. The versionCode is an integer that can be evaluated in programs to determine the upgrade or downgrade relationship. The versionName represents a human readable format that can have major and minor revisions declared.

The application element defines the icon and label the user sees from the Android device menu. The label is a string and should be short enough to display under the icon on a user's device. Generally the name can be up to two words of ten characters each without being cut off.

The activity element defines the main activity that is launched when the application is started and the name shown in the title bar when the activity is active. Here, the Java package name needs to be specified, which is com.cookbook.simple_activity. SimpleActivity in this case. Because the Java package name is usually the same as the Android package name, the shorthand notation is often used: .SimpleActivity. However, it is best to remember that the Android package and Java package are distinct.

The intent-filter element informs the Android system of the capabilities of the component. It can have multiple action, category, or data elements for this purpose. This is seen as it is utilized in different recipes.

The uses-sdk element defines the application programming interface (API) level required to run this application. In general, the API level is specified as follows:

<uses-sdk android:minSdkVersion="integer"
          android:targetSdkVersion="integer"
          android:maxSdkVersion="integer" />

Because the Android OS is constructed to be forward compatible, the maxSdkVersion is highly discouraged and not even adhered on devices with Android 2.0.1 or later. Specifying the targetSdkVersion is not required, but allows devices of the same SDK version to disable compatibility settings that might speed up operation. The minSdkVersion should always be specified to ensure the application does not crash when run on a platform that does not support the required features in the application. Always choose the lowest API level possible when specifying this.

The AndroidManifest can also contain permission settings needed to run the application. More complete details about the options are provided in later chapters, but this suffices to cover the recipes in this chapter.

Renaming Parts of an Application

Sometimes a portion of an Android project needs to be renamed. Maybe a file was copied manually into the project, such as from this book. Maybe the application name has changed during development, and it needs to be reflected in the filesystem tree. Automatic tools help with this and ensure cross-references are automatically updated. For example, in the Eclipse IDE, the different ways to rename portions of an application are

  • Rename the Android project, as follows:
    1. Right-click the project and Refactor u2192.jpg Move to a new directory in the filesystem.
    2. Right-click the project and Refactor u2192.jpg Rename the project.
  • Rename an Android package, as follows:
    1. Right-click the package and Refactor u2192.jpg Rename the package.
    2. Edit the AndroidManifest.xml to ensure the new package name is reflected.
  • Rename an Android class (such as the major components Activity, Service, BroadcastReceiver, ContentProvider), as follows:
    1. Right-click the .java file and Refactor u2192.jpg Rename the class.
    2. Edit the AndroidManifest.xml to ensure the android:name has the new component name.

Note that renaming other files, such as XML files, usually requires manually changing the corresponding references in the Java code.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020