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

Method

Purpose

Log.e()

Log errors

Log.w()

Log warnings

Log.i()

Log informational messages

Log.d()

Log debug messages

Log.v()

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:

Log.i(DEBUG_TAG,
    "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

Method

Purpose

MediaPlayer.create()

Creates a new media player with a given target to play

MediaPlayer.start()

Starts media playback

MediaPlayer.stop()

Stops media playback

MediaPlayer.release()

Releases the media player resources

Uri.parse()

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);
        mp.start();
    }
    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) {
        mp.stop();
        mp.release();
    }
    super.onStop();
}

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)
            getSystemService(LOCATION_SERVICE);
        Location recentLoc = locMgr.
            getLastKnownLocation(LocationManager.GPS_PROVIDER);
        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