Home > Articles > Mobile Application Development & Programming

📄 Contents

  1. Testing Your Development Environment
  2. Building Your First Android Application
  3. Summary
  • Print
  • + Share This
This chapter is from the book

Building Your First Android Application

Now it’s time to write your first Android application from scratch. To get your feet wet, you will start with a simple “Hello World” application and build upon it to explore some of the features of the Android platform in more detail.

Creating and Configuring a New Android Project

You can create a new Android application in much the same way as when you added the Snake application to your Eclipse workspace.

The first thing you need to do is create a new project in your Eclipse workspace. The Android Project Wizard creates all the required files for an Android application. Follow these steps within Eclipse to create a new project:

  1. Choose File, New, Android Project, or choose the Android Project creator icon, which looks like a folder (03icon03.jpg), on the Eclipse toolbar.
  2. Choose a project name, as shown in Figure 3.10. In this case, name the project MyFirstAndroidApp.
    Figure 3.10

    Figure 3.10 Configuring a new Android project.

  3. Choose a location for the project files. Because this is a new project, select the Create New Project in Workspace radio button. Check the Use Default Location check box or change the directory to wherever you want to store the source files. Click Next.
  4. Select a build target for your application, as shown in Figure 3.11. Choose a target that is compatible with the Android devices you have in your possession. For this example, you might use the Android 2.3.3 target or, for Ice Cream Sandwich devices, Android 4.0 (API Level 14). Click Next.
    Figure 3.11

    Figure 3.11 Choosing a build target for a new Android project.

  5. Configure your application information. Choose an application name. The application name is the “friendly” name of the application and the name shown with the icon on the application launcher. In this case, the application name is “My First Android App.”
  6. Choose a package name. Here you should follow standard package namespace conventions for Java. Because all our code examples in this book fall under the com.androidbook.* namespace, we will use the package name com.androidbook.myfirstandroidapp, but you are free to choose your own package name.
  7. Check the Create Activity check box. This instructs the wizard to create a default launch activity for the application. Call this Activity class MyFirstAndroidAppActivity.
  8. Set the minimum SDK version. This value should be the same or lower than the target SDK API level. Because our application will be compatible with just about any Android device, you can set this number low (like to 4 to represent Android 1.6) or at the target API level to avoid annoying warnings in Eclipse. Make sure you set the minimum SDK version to encompass any test devices you have available so you can successfully install the application on them.

    Your project settings should look like Figure 3.12.

    Figure 3.12

    Figure 3.12 Configuring My First Android App using the Android Project Wizard.

  9. Finally, click the Finish button.

Core Files and Directories of the Android Application

Every Android application has a set of core files that are created and used to define the functionality of the application. The following files are created by default with a new Android application:

  • AndroidManifest.xml—The central configuration file for the application. It defines your application’s capabilities and permissions as well as how it runs.
  • project.properties—A generated build file used by Eclipse and the Android ADT plug-in. It defines your application’s build target and other build system options, as required. Do not edit this file.
  • proguard.cfg—A generated build file used by Eclipse, ProGuard, and the Android ADT plug-in. Edit this file to configure your code optimization and obfuscation settings for release builds.
  • /src folder—Required folder for all source code.
  • /src/com/androidbook/myfirstandroidapp/MyFirstAndroidAppActivity.java—Main entry point to this application, named MyFirstAndroidAppActivity. This activity has been defined as the default launch activity in the Android manifest file.
  • /gen/com/androidbook/myfirstandroidapp/R.java—A generated resource management source file. Do not edit this file.
  • /assets folder—Required folder where uncompiled file resources can be included in the project. Application assets are pieces of application data (files, directories) that you do not want managed as application resources.
  • /res folder—Required folder where all application resources are managed. Application resources include animations, drawable graphics, layout files, data-like strings and numbers, and raw files.
  • /res/drawable-*—Application icon graphic resources are included in several sizes for different device screen resolutions.
  • /res/layout/main.xml—Layout resource file used by MyFirstAndroidAppActivity to organize controls on the main application screen.
  • /res/values/strings.xml—The resource file where string resources are defined.

A number of other files are saved on disk as part of the Eclipse project in the workspace. However, the files and resource directories included in the list here are the important project files you will use on a regular basis.

Creating an AVD for Your Project

The next step is to create an AVD that describes what type of device you want to emulate when running the application. For this example, we can use the AVD we created for the Snake application. An AVD describes a device, not an application. Therefore, you can use the same AVD for multiple applications. You can also create similar AVDs with the same configuration but different data (such as different applications installed and different SD card contents).

Creating a Launch Configuration for Your Project

Next, you must create a Run and Debug launch configuration in Eclipse to configure the circumstances under which the MyFirstAndroidApp application builds and launches. The launch configuration is where you configure the emulator options to use and the entry point for your application.

You can create Run configurations and Debug configurations separately, with different options for each. Begin by creating a Run configuration for the application. Follow these steps to create a basic Run configuration for the MyFirstAndroidApp application:

  1. Choose Run, Run Configurations (or right-click the project and choose Run As).
  2. Double-click Android Application.
  3. Name your Run configuration MyFirstAndroidAppRunConfig.
  4. Choose the project by clicking the Browse button and choosing the MyFirstAndroidApp project.
  5. Switch to the Target tab and set the Device Target Selection Mode to Manual.

Now create a Debug configuration for the application. This process is similar to creating a Run configuration. Follow these steps to create a basic Debug configuration for the MyFirstAndroidApp application:

  1. Choose Run, Debug Configurations (or right-click the project and choose Debug As).
  2. Double-click Android Application.
  3. Name your Debug configuration MyFirstAndroidAppDebugConfig.
  4. Choose the project by clicking the Browse button and choosing the MyFirstAndroidApp project.
  5. Switch to the Target tab and set the Device Target Selection Mode to Manual.
  6. Click Apply and then click Close.

You now have a Debug configuration for your application.

Running Your Android Application in the Emulator

Now you can run the MyFirstAndroidApp application using the following steps:

  1. Choose the Run As icon drop-down menu on the toolbar (03icon04.jpg).
  2. Pull the drop-down menu and choose the Run configuration you created. (If you do not see it listed, choose the Run Configurations... item and select the appropriate configuration. The Run configuration shows up on this drop-down list the next time you run the configuration.)
  3. Because you chose the Manual Target Selection mode, you are now prompted for your emulator instance. Change the selection to Launch a New Android Virtual Device and then select the AVD you created, as shown in Figure 3.13. Here you can choose from an already-running emulator or launch a new instance with an AVD that is compatible with the application settings.
    Figure 3.13

    Figure 3.13 Manually choosing a target selection mode.

  4. The Android emulator starts up, which might take a moment.
  5. Click the Menu button or push the slider to the right to unlock the emulator.
  6. The application starts, as shown in Figure 3.14.
    Figure 3.14

    Figure 3.14 My First Android App running in the emulator.

  7. Click the Back button in the Emulator to end the game or click Home to suspend it.
  8. Click the grid button to browse all installed applications. Your screen looks something like Figure 3.15.
    Figure 3.15

    Figure 3.15 The My First Android App icon shown in the application listing.

  9. Click the My First Android Application icon to launch the application again.

Debugging Your Android Application in the Emulator

Before we go any further, you need to become familiar with debugging in the emulator. To illustrate some useful debugging tools, let’s manufacture an error in the My First Android Application.

In your project, edit the source file called MyFirstAndroidApp.java. Create a new method called forceError() in your class and make a call to this method in your Activity class’s onCreate() method. The forceError() method forces a new unhandled error in your application.

The forceError() method should look something like this:

public void forceError() {
    if(true) {
        throw new Error("Whoops");

It’s probably helpful at this point to run the application and watch what happens. Do this using the Run configuration first. In the emulator, you see that the application has stopped unexpectedly. You are prompted by a dialog that enables you to forcefully close the application, as shown in Figure 3.16.

Figure 3.16

Figure 3.16 My First Android App crashing gracefully.

Shut down the application but keep the emulator running. Now it’s time to debug. You can debug the MyFirstAndroidApp application using the following steps:

  1. Choose the Debug As icon drop-down menu on the toolbar.
  2. Pull the drop-down menu and choose the Debug configuration you created. (If you do not see it listed, choose the Debug Configurations... item and select the appropriate configuration. The Debug configuration shows up on this drop-down list the next time you run the configuration.)
  3. Continue as you did with the Run configuration and choose the appropriate AVD and then launch the emulator again, unlocking it if needed.

It takes a moment for the debugger to attach. If this is the first time you’ve debugged an Android application, you may need to click through some dialogs, such as the one shown in Figure 3.17, the first time your application attaches to the debugger.

Figure 3.17

Figure 3.17 Switching debug perspectives for Android emulator debugging.

In Eclipse, use the Debug perspective to set breakpoints, step through code, and watch the LogCat logging information about your application. This time, when the application fails, you can determine the cause using the debugger. You might need to click through several dialogs as you set up to debug within Eclipse. If you allow the application to continue after throwing the exception, you can examine the results in the Debug perspective of Eclipse. If you examine the LogCat logging pane, you see that your application was forced to exit due to an unhandled exception (see Figure 3.18).

Figure 3.18

Figure 3.18 Debugging My First Android App in Eclipse.

Specifically, there’s a red AndroidRuntime error: java.lang.Error: Whoops. Back in the emulator, click the Force Close button. Now set a breakpoint on the forceError() method by right-clicking the left side of the line of code and choosing Toggle Breakpoint (or pressing Ctrl+Shift+B).

In the emulator, restart your application and step through your code. You see that your application has thrown the exception and then the exception shows up in the Variable Browser pane of the Debug Perspective. Expanding its contents shows that it is the “Whoops” error.

This is a great time to crash your application repeatedly and get used to the controls. While you’re at it, switch over to the DDMS perspective. You note the emulator has a list of processes running on the device, such as system_process and com.android.phone. If you launch MyFirstAndroidApp, you see com.androidbook.myfirstandroidapp show up as a process on the emulator listing. Force the app to close because it crashes, and note that it disappears from the process list. You can use DDMS to kill processes, inspect threads and the heap, and access the phone file system.

Adding Logging Support to Your Android Application

Before you start diving into the various features of the Android SDK, you should familiarize yourself with logging, a valuable resource for debugging and learning Android. Android logging features are in the Log class of the android.util package. Some helpful methods in the android.util.Log class are shown in Table 3.1.

Table 3.1 Commonly Used Logging Methods




Log errors


Log warnings


Log informational messages


Log debug messages


Log verbose messages

To add logging support to MyFirstAndroidApp, edit the file MyFirstAndroidApp.java. First, you must add the appropriate import statement for the Log class:

import android.util.Log;

Next, within the MyFirstAndroidApp class, declare a constant string that you use to tag all logging messages from this class. You can use the LogCat utility within Eclipse to filter your logging messages to this DEBUG_TAG tag string:

private static final String DEBUG_TAG= "MyFirstAppLogging";

Now, within the onCreate() method, you can log something informational:

    "In the onCreate() method of the MyFirstAndroidAppActivity Class");

While you’re here, you must comment out your previous forceError() call so that your application doesn’t fail. Now you’re ready to run MyFirstAndroidApp. Save your work and debug it in the emulator. You notice that your logging messages appear in the LogCat listing, with the Tag field MyFirstAppLogging (see Figure 3.19).

Figure 3.19

Figure 3.19 A LogCat log for My First Android App.

Adding Some Media Support to Your Application

Next, let’s add some pizzazz to MyFirstAndroidApp by having the application play an MP3 music file. Android media player features are found in the MediaPlayer class of the android.media package.

You can create MediaPlayer objects from existing application resources or by specifying a target file using a Uniform Resource Identifier (URI). For simplicity, we begin by accessing an MP3 using the Uri class from the android.net package.

Some methods in the android.media.MediaPlayer and android.net.Uri classes are shown in Table 3.2.

Table 3.2 Commonly Used MediaPlayer and URI Parsing Methods




Creates a new media player with a given target to play


Starts media playback


Stops media playback


Releases the media player resources


Instantiates a Uri object from an appropriately formatted URI address

To add MP3 playback support to MyFirstAndroidApp, edit the file MyFirstAndroidApp.java. First, you must add the appropriate import statements for the MediaPlayer class:

import android.media.MediaPlayer;
import android.net.Uri;

Next, within the MyFirstAndroidApp class, declare a member variable for your MediaPlayer object:

private MediaPlayer mp;

Now, create a new method called playMusicFromWeb() in your class and make a call to this method in your onCreate() method. The playMusicFromWeb() method creates a valid Uri object, creates a MediaPlayer object, and starts the MP3 playing. If the operation should fail for some reason, the method logs a custom error with your logging tag. The playMusicFromWeb() method should look something like this:

public void playMusicFromWeb() {
     try {
        Uri file = Uri.parse("http://www.perlgurl.org/podcast/archives"
            + "/podcasts/PerlgurlPromo.mp3");
        mp = MediaPlayer.create(this, file);
    catch (Exception e) {
        Log.e(DEBUG_TAG, "Player failed", e);

As of Android 4.0 (API Level 14), using the MediaPlayer class to access media content on the Web requires the INTERNET permission to be registered in the application’s Android manifest file. Finally, your application requires special permissions to access location-based functionality. You must register this permission in your AndroidManifest.xml file. To add permissions to your application, perform the following steps:

  1. Double-click the AndroidManifest.xml file.
  2. Switch to the Permissions tab.
  3. Click the Add button and choose Uses Permission.
  4. In the right pane, select android.permission.INTERNET.
  5. Save the file.

Later on, you’ll learn all about the various Activity states and callbacks that could contain portions of the playMusicFromWeb() method. For now, know that the onCreate() method is called every time the user navigates to the Activity (forward or backward) and whenever he or she rotates the screen or causes other device configuration changes. This doesn’t cover all cases, but will work well enough for this example.

And finally, you want to cleanly exit when the application shuts down. To do this, you need to override the onStop() method of your Activity class and stop the MediaPlayer object and release its resources. The onStop() method should look something like this:

protected void onStop() {
    if (mp != null) {

Now, if you run MyFirstAndroidApp in the emulator (and you have an Internet connection to grab the data found at the URI location), your application plays the MP3. When you shut down the application, the MediaPlayer is stopped and released appropriately.

Adding Location-Based Services to Your Application

Your application knows how to say “Hello” and play some music, but it doesn’t know where it’s located. Now is a good time to become familiar with some simple location-based calls to get the GPS coordinates. To have some fun with location-based services and maps integration, you will use some of the Google applications available on typical Android devices—specifically, the Maps application. You do not need to create another AVD, because you included the Google APIs as part of the target for the AVD you already created.

Configuring the Location of the Emulator

The emulator does not have location sensors, so the first thing you need to do is seed your emulator with some GPS coordinates. You can find the exact steps for how to do this in Appendix A, in the section “Configuring the GPS Location of the Emulator.” After you have configured the location of your emulator, the Maps application should now display your simulated location, as shown in Figure 3.20.

Figure 3.20

Figure 3.20 Setting the location of the emulator to Yosemite Valley.

Your emulator now has a simulated location: Yosemite Valley!

Finding the Last Known Location

To add location support to MyFirstAndroidApp, edit the file MyFirstAndroidApp.java. First, you must add the appropriate import statements:

import android.location.Location;
import android.location.LocationManager;

Now, create a new method called getLocation() in your class and make a call to this method in your onCreate() method. The getLocation() method gets the last known location on the device and logs it as an informational message. If the operation fails for some reason, the method logs an error.

The getLocation() method should look something like this:

public void getLocation() {
    try {
        LocationManager locMgr = (LocationManager)
        Location recentLoc = locMgr.
        Log.i(DEBUG_TAG, "loc: " + recentLoc.toString());
    catch (Exception e) {
        Log.e(DEBUG_TAG, "Location failed", e);

Finally, your application requires special permissions to access location-based functionality. You must register this permission in your AndroidManifest.xml file. To add location-based service permissions to your application, perform the following steps:

  1. Double-click the AndroidManifest.xml file.
  2. Switch to the Permissions tab.
  3. Click the Add button and choose Uses Permission.
  4. In the right pane, select android.permission.ACCESS_FINE_LOCATION.
  5. Save the file.

Now, if you run My First Android App in the emulator, your application logs the GPS coordinates you provided to the emulator as an informational message, viewable in the LogCat pane of Eclipse.

Debugging Your Application on the Hardware

You mastered running applications in the emulator. Now let’s put the application on real hardware. First, you must register your application as debuggable in your AndroidManifest.xml file. To do this, perform the following steps:

  1. Double-click the AndroidManifest.xml file.
  2. Change to the Application tab.
  3. Set the Debuggable application attribute to true.
  4. Save the file.

You can also modify the application element of the AndroidManifest.xml file directly with the android:debuggable attribute, as shown here:

<application ... android:debuggable="true">

Now, connect an Android device to your computer via USB and re-launch the Run configuration or Debug configuration of the application. Because you chose Manual mode for the configuration, you should now see a real Android device listed as an option in the Android Device Chooser (see Figure 3.21).

Figure 3.21

Figure 3.21 Android Device Chooser with USB-connected Android device.

Choose the Android device as your target, and you see that the My First Android App application gets loaded onto the Android device and launched, just as before. Provided you have enabled the development debugging options on the device, you can debug the application here as well. You can tell the device is actively using a USB debugging connection, because a little Android bug-like icon appears in the notification bar (03icon05.jpg). Figure 3.22 shows a screenshot of the application running on a real device (in this case, a smartphone running Android 2.3.2).

Figure 3.22

Figure 3.22 My First Android App running on Android device hardware.

Debugging on the device is much the same as debugging on the emulator, but with a couple of exceptions. You cannot use the emulator controls to do things such as send an SMS or configure the location to the device, but you can perform real actions (true SMS, actual location data) instead.

  • + Share This
  • 🔖 Save To Your Account

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.


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.


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.


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.


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


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


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.


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.


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