Writing Your First Android Application - An Overview of the Android Platform - Introduction to Android Application Development, Fourth Edition (2014)

Introduction to Android Application Development, Fourth Edition (2014)

Part I. An Overview of the Android Platform

Chapter 3. Writing Your First Android Application

You should now have a workable Android development environment set up on your computer. Ideally, you have an Android device as well. Now it’s time for you to start writing some Android code. In this chapter, you learn how to install the Android sample applications and to add and create Android projects from within the Android IDE. You also learn how to verify that your Android development environment is set up correctly. You then write and debug your first Android application in the software emulator and on an Android device.


Image Note

The Android Development Tool Bundles are updated frequently. We have made every attempt to provide the latest steps for the latest tools. However, these steps and the user interfaces described in this chapter may change at any time. Please refer to the Android development website (http://d.android.com/sdk/index.html) and our book website (http://introductiontoandroid.blogspot.com) for the latest information.


Testing Your Development Environment

The best way to make sure you configured your development environment correctly is to run an existing Android application. You can do this easily by using one of the sample applications provided as part of the Android SDK in the samples subdirectory found where your Android SDK is installed.

Within the Android SDK sample applications, you will find a classic game called Snake (http://en.wikipedia.org/wiki/Snake_(video_game)). To build and run the Snake application, you must create a new Android project in your Android IDE workspace based on the existing Android sample project, create an appropriate Android Virtual Device (AVD) profile, and configure a launch configuration for that project. After you have everything set up correctly, you can build the application and run it on the Android emulator and on an Android device. By testing your development environment with a sample application, you can rule out project configuration and coding issues and focus on determining whether the tools are set up properly for Android development. After this fact has been established, you can move on to writing and compiling your own applications.

Adding the Android Samples Using the SDK Manager

One quick way to learn how to develop Android applications is by reviewing an application that has already been created. There are many Android applications available for this purpose, but first we must download them. Here is how:

1. From within the Android IDE, click the Android SDK Manager icon (Image) to open the Android SDK Manager. You should see a dialog similar to that in Figure 3.1.

Image

Figure 3.1 The Android SDK Manager.

2. You now need to install the Samples for SDK listed under Android 4.3 (API 18), so go ahead and select this item. You may also want to install a few additional items along with the samples, so select the following for installation (shown in Figure 3.1): Documentation for Android SDKand Google APIs. Then click Install Packages. Make sure that the proper SDK Tools, Platform-tools, Build-tools, SDK Platform, and System Image are installed as well; if they are not, you should select those for installation now, too.

3. A new dialog appears (see Figure 3.2) asking you to accept the license agreement for the packages that you will be installing. You may accept or reject each license individually by highlighting a particular package in the left pane and choosing Accept or Reject, or you can accept them all at once by highlighting Android SDK License in the left pane and choosing Accept License. Let’s accept all the licenses together by selecting Android SDK License in the left pane, choosing Accept License, and then clicking Install. This will initiate the installation of the selected packages. Wait until the installation is complete.

Image

Figure 3.2 Accepting the license agreements.


Image Tip

To learn more about how to download the Android SDK sample applications for your particular development platform, see http://d.android.com/tools/samples/index.html.


Now that the installation is completed, you are ready to begin loading Android sample projects into your workspace.

Adding the Snake Project to Your Android IDE Workspace

To add the Snake project to your Android IDE workspace, follow these steps:

1. Choose File, New, Other....

2. Choose Android, Android Sample Project (see Figure 3.3). Click Next.

Image

Figure 3.3 Creating a new Android sample project.

3. Choose your build target (see Figure 3.4). In this case, we’ve picked Android 4.3, API Level 18, from the Android Open Source Project. Click Next.

Image

Figure 3.4 Choose an API level for the sample.

4. Select which sample you want to create (see Figure 3.5). Choose Snake.

Image

Figure 3.5 Picking the Snake sample project.

5. Click Finish. You now see the Snake project files in your workspace (see Figure 3.6).

Image

Figure 3.6 The Snake project files.


Image Warning

Occasionally the Android IDE shows an error like “Project ‘Snake’ is missing required source folder: gen” when you’re adding an existing project to the workspace. If this happens, navigate to the /gen directory and delete the files within. These files are automatically regenerated and the error should disappear. Performing a Clean operation followed by a Build operation does not always solve this problem.


Creating an AVD for Your Snake Project

The next step is to create an AVD that describes what type of device you want to emulate when running the Snake application. This AVD profile describes what type of device you want the emulator to simulate, including which Android platform to support. You do not need to create new AVDs for each application, only for each device you want to emulate. You can specify different screen sizes and orientations, and you can specify whether the emulator has an SD card and, if it does, what capacity the card has.

For the purposes of this example, an AVD for the default installation of Android 4.3 suffices. Here are the steps to create a basic AVD:

1. Launch the Android Virtual Device Manager from within the Android IDE by clicking the little Android device icon on the toolbar (Image). If you cannot find the icon, you can also launch the manager through the Window menu of the Android IDE. You should now see the Android Virtual Device Manager window (see Figure 3.7).

Image

Figure 3.7 Android Virtual Device Manager.

2. Click the New button.

3. Choose a name for your AVD. Because we are going to take all the defaults, give this AVD a name of AndroidVanilla.

4. Choose a device. This option controls the different resolutions of the emulator. We want to choose a typical device size, so in this case, select Nexus 4 (4.7”, 768 × 1280: xhdpi). This option most directly correlates to the popular Nexus 4 Google-branded device. Feel free to choose the most appropriate device to match the Android device on which you plan to run the application.

5. Choose a build target. We want a typical Android 4.3 device, so choose Google APIs (Google Inc.) – API Level 18 from the drop-down menu. In addition to including the Android APIs, this option will also include the Google APIs and applications, such as the Maps application, as part of the platform image. Although we could choose the standard Android 4.3 – APIs Level 18 for this project, it is important to be aware of the additional options the Google APIs provide.

6. For the Memory Options setting, you may have to try different values for optimal performance depending on the memory configuration of your development machine. The default RAM value for this virtual device is 1907 and the VM Heap is 64. If your machine is older and does not have a lot of memory, you may need to lower this value significantly to something like 512. The development machine used for this book has 8GB of RAM with a fairly powerful quad-core processor, and the RAM value we decided to use is 768 with the VM Heap set to 64.

7. Choose an SD card capacity, in either kibibytes or mibibytes. (Not familiar with kibibytes? See this Wikipedia entry: http://en.wikipedia.org/wiki/Kibibyte.) This SD card image will take up space on your hard drive and may also take a long time to allocate, so choose something reasonable, such as 1024MiB.

8. Seriously consider enabling the Snapshot feature listed under Emulation Options. This greatly improves emulator startup performance. See Appendix B, “Quick-Start Guide: The Android Emulator,” for details.

Your project settings will look like Figure 3.8.

Image

Figure 3.8 Creating a new AVD.

9. Click the OK button to create the AVD, and then wait for the operation to complete.

10. You should now see the AVD that you just created listed within your Android Virtual Device Manager (see Figure 3.9).

Image

Figure 3.9 The new AVD is now listed.

For more information on creating different types of AVDs, check out Appendix B.

Creating a Launch Configuration for Your Snake Project

Next, you must create a launch configuration in the Android IDE to configure under what circumstances the Snake 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, each with different options. These configurations are created under the Run menu in the Android IDE (Run, Run Configurations... and Run, Debug Configurations...). Follow these steps to create a basic Debugconfiguration for the Snake application:

1. Choose Run, Debug Configurations....

2. Double-click Android Application to create a new configuration.

3. Name your Debug configuration SnakeDebugConfig.

4. Choose the project by clicking the Browse button and choosing the Snake project (see Figure 3.10).

Image

Figure 3.10 Naming the Debug configuration in the Android IDE.

5. Switch to the Target tab and, from the preferred AVD list, choose the AndroidVanilla AVD created earlier, as shown in Figure 3.11.

Image

Figure 3.11 Target AVD for the Debug configuration in the Android IDE.

6. Choose Apply and then Close.

You can set other emulator and launch options on the Target and Common tabs, but for now we are leaving the defaults as they are.

Running the Snake Application in the Android Emulator

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

1. Choose the Debug As icon drop-down menu on the toolbar (Image).

2. Pull the drop-down menu and choose the SnakeDebugConfig you created. If you do not see the SnakeDebugConfig listed, find it in the Debug Configurations... listing and click the Debug button. Subsequent launches can be initiated from the little bug drop-down.

3. The Android emulator starts up; this might take a few moments to initialize. Then the application will be installed or reinstalled onto the emulator.


Image Tip

It can take a long time for the emulator to start up, even on very fast computers. You might want to leave it around while you work and reattach to it as needed. The tools in the Android IDE handle reinstalling the application and relaunching it, so you can more easily keep the emulator loaded all the time. This is another reason to enable the Snapshot feature for each AVD. You can also use the Start button on the Android Virtual Device Manager to load an emulator before you need it. Launching the AVD this way also gives you some additional options such as screen scaling (see Figure 3.12), which can be used to either fit the AVD on your screen if it’s very high resolution or more closely emulate the size it might be on real hardware.


Image

Figure 3.12 Configuring AVD launch options.

4. If necessary, swipe the screen from left to right to unlock the emulator, as shown in Figure 3.13.

Image

Figure 3.13 The Android emulator launching (locked).

5. The Snake application starts and you can play the game, as shown in Figure 3.14.

Image

Figure 3.14 The Snake game in the Android emulator.

You can interact with the Snake application through the emulator and play the game. You can also launch the Snake application from the All Apps screen at any time by clicking its application icon. There is no need to shut down and restart the emulator every time you rebuild and reinstall your application for testing. Simply leave the emulator running on your computer in the background while you work in the Android IDE and then redeploy using the Debug configuration again.

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.


Image Tip

The code examples provided in this chapter are taken from the MyFirstAndroidApp application. The source code for the MyFirstAndroidApp application is provided for download on the book’s website.


Creating and Configuring a New Android Project

You can create a new Android application in much the same way that you added the Snake application to your Android IDE workspace.

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

1. Choose File, New, Android Application Project on the Android IDE toolbar.

2. Choose an application name as shown in Figure 3.15. The application name is the “friendly” name of the application and the name shown with the icon on the application launcher. Name the application My First Android App. This will automatically create a project name ofMyFirstAndroidApp, but you are free to change this to a name of your choosing.

Image

Figure 3.15 Configuring a new Android project.

3. We should also change the package name, using reverse domain name notation (http://en.wikipedia.org/wiki/Reverse_domain_name_notation), to com.introtoandroid.myfirstandroidapp. The Minimum Required SDK version should be the first SDK API level you plan to target. Because our application will be compatible with just about any Android device, you can set this number low (such as to 4 to represent Android 1.6) or at the target API level to avoid any warnings in the Android IDE. 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. The default options are just fine for our example. Click Next.

4. Keep the rest of the New Android Application settings at their defaults, unless you want to change the directory of where the source files will be stored. Click Next (see Figure 3.16).

Image

Figure 3.16 Configuring Android project options.

5. Leave the Configure Launcher Icon settings at their defaults. This option screen would allow us to define how our application launcher icon appears, but for this example, we will use the standard icon set included with the Android SDK. Choose Next (see Figure 3.17).

Image

Figure 3.17 Configuring the launcher icon for our Android project.

6. The Create Activity wizard allows us to include a default launch activity by type. We will leave the settings as is and choose Next (see Figure 3.18).

Image

Figure 3.18 Creating an Activity for our Android project.

7. Choose an Activity Name. Call this Activity class MyFirstAndroidAppActivity. The Layout Name should automatically change to a name resembling what you just entered. Finally, click the Finish button (see Figure 3.19) to create the application.

Image

Figure 3.19 Choosing an Activity Name.

8. The Android IDE should now display our first application created using the wizard with our layout file open and ready for editing (see Figure 3.20).

Image

Figure 3.20 Our first application created with the wizard.

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:

Image AndroidManifest.xml—the central configuration file for the application. It defines your application’s capabilities and permissions as well as how it runs.

Image ic_launcher-web.png—This is a high-resolution 32-bit 512 × 512 PNG application icon that is required and used for your application listing in the Google Play store. The size of this icon should not exceed 1024KB.

Image proguard-project.txt—a generated build file used by the Android IDE and ProGuard. Edit this file to configure your code optimization and obfuscation settings for release builds.

Image project.properties—a generated build file used by the Android IDE. It defines your application’s build target and other build system options, as required. Do not edit this file.

Image /src—required folder for all source code.

Image /src/com/introtoandroid/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.

Image /gen—required folder for all autogenerated files.

Image /gen/com/introtoandroid/myfirstandroidapp/BuildConfig.java—a generated source file used when debugging your applications. Do not edit this file.

Image /gen/com/introtoandroid/myfirstandroidapp/R.java—a generated resource management source file. Do not edit this file.

Image /assets—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.

Image /bin—folder for creating autogenerated files for producing your application’s APK file.

Image /libs—folder for including any .jar library projects.

Image /libs/android-support-v4.jar—This support library can be added to your projects to bring newer Android APIs to older devices running older versions of Android.

Image /res—required folder where all application resources are managed. Application resources include animations, drawable graphics, layout files, datalike strings and numbers, and raw files.

Image /res/drawable-*—Application icon graphics resources are included in several sizes for different device screen resolutions.

Image /res/layout—required folder that comprises one or more layout resource files, each file managing a different UI or App Widget layout for your application.

Image /res/layout/activity_my_first_android_app.xml—layout resource file used by MyFirstAndroidAppActivity to organize controls on the main application screen.

Image /res/menu—folder for including XML files for defining Android application menus.

Image /res/menu/my_first_android_app.xml—menu resource file used by MyFirstAndroidAppActivity defining a menu item for Settings.

Image /res/values*—folders for including XML files for defining Android application dimensions, strings, and styles.

Image /res/values/dimens.xml—dimension resource file used by MyFirstAndroidAppActivity defining default screen margins.

Image /res/values/strings.xml—string resource file used by MyFirstAndroidAppActivity defining string variables that may be reused throughout the application.

Image /res/values/styles.xml—style resource file used by MyFirstAndroidAppActivity to define the application theme.

Image /res/values-sw600dp/dimens.xml—dimension resource file for overriding the res/values/dimens.xml for defining dimensions for 7-inch tablets.

Image /res/values-sw720dp-land/dimens.xml—dimension resource file for overriding the res/values/dimens.xml for defining dimensions for 10-inch tablets in landscape mode.

Image /res/values-v11/styles.xml—style resource file for overriding the res/values/styles.xml for devices running Android with an API greater than or equal to 11.

Image /res/values-v14/styles.xml—style resource file for overriding the res/values/styles.xml for devices running Android with an API greater than or equal to 14.

A number of other files are saved on disk as part of the Android IDE 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 the Android IDE 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 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 Deployment Target Selection Mode to Always prompt to pick device.

6. Click Apply and then click Close.


Image Tip

If you leave the Deployment Target Selection Mode set to Automatic when you choose Run or Debug in the Android IDE, your application is automatically installed and run on the device if the device is plugged in. Otherwise, the application starts in the emulator with the specified AVD. By choosing Always prompt to pick device, you are always prompted for whether (a) you want your application to be launched in an existing emulator; (b) you want your application to be launched in a new emulator instance and are allowed to specify an AVD; or (c) you want your application to be launched on the device (if it’s plugged in). If any emulator is already running, the device is then plugged in, and the mode is set to Automatic, you see this same prompt, too.


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 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 Deployment Target Selection Mode to Always prompt to pick device.

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 (Image).

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 Always prompt to pick device 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. Here, you can choose from an already-running emulator or launch a new instance with an AVD that is compatible with the application settings, as shown in Figure 3.21.

Image

Figure 3.21 Manually choosing a deployment 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.22.

Image

Figure 3.22 My First Android App running in the emulator.

7. Click the Back button in the emulator to end the application, or click Home to suspend it.

8. Click the All Apps button (see Figure 3.23) found in the Favorites tray to browse all installed applications from the All Apps screen.

Image

Figure 3.23 The All Apps button.

9. Your screen should now look something like Figure 3.24. Click the My First Android App icon to launch the application again.

Image

Figure 3.24 The My First Android App icon shown in the All Apps screen.

Debugging Your Android Application in the Emulator

Before going 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 App.

In your project, edit the source file called MyFirstAndroidAppActivity.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 force the application to close, as shown inFigure 3.25.

Image

Figure 3.25 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.26, the first time your application attaches to the debugger.

Image

Figure 3.26 Switching to Debug perspective for Android emulator debugging.

In the Android IDE, 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 the Android IDE. If you allow the application to continue after throwing the exception, you can examine the results in the Debug perspective of the Android IDE. If you examine the LogCat logging pane, you see that your application was forced to exit due to an unhandled exception (see Figure 3.27).

Image

Figure 3.27 Debugging MyFirstAndroidApp in the Android IDE.

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 double-clicking).


Image Tip

In the Android IDE, you can step through code using Step Into (F5), Step Over (F6), Step Return (F7), or Resume (F8). On Mac OS X, you might find that the F8 key is mapped globally. If you want to use the keyboard convenience command, you might want to change the keyboard mapping in the Android IDE by choosing Window, Preferences, General, Keys and then finding the entry for Resume and changing it to something else. Alternatively, you can change the Mac OS X global mapping by going to System Preferences, Keyboard & Mouse,Keyboard Shortcuts and then changing the mapping for F8 to something else.


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. Note that 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.introtoandroid.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. See Table 3.1 for some helpful methods in the android.util.Log class.

Image

Table 3.1 Commonly Used Logging Methods

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;


Image Tip

To save time in the Android IDE, you can use the imported classes in your code and add the imports needed by hovering over the imported class name and choosing the Add Imported Class QuickFix option.

You can also use the Organize Imports command (Ctrl+Shift+O in Windows or Command+Shift+O on a Mac) to have the Android IDE automatically organize your imports. This removes unused imports and adds new ones for packages used but not imported. If a naming conflict arises, as it often does with the Log class, you can choose the package you intended to use.


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 the Android IDE 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. Notice that your logging messages appear in the LogCat listing, with the Tag fieldMyFirstAppLogging (see Figure 3.28).

Image

Figure 3.28 A LogCat log for MyFirstAndroidApp.

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 URI. For simplicity, we begin by accessing an MP3 using the Uri class from the android.net package.

Table 3.2 shows some methods used in the android.media.MediaPlayer and android.net.Uri classes.

Image

Table 3.2 Commonly Used MediaPlayer and Uri Parsing Methods

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.2.2 (API Level 17), 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 (see Figure 3.29).

Image

Figure 3.29 Adding the INTERNET permission in the manifest.

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();
}


Image Tip

In the Android IDE, you can right-click within the class and choose Source (or press Alt+Shift+S). Choose the option Override/Implement Methods and select the onStop() method.


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 map 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 B, “Quick-Start Guide: The Android Emulator,” in the section “Configuring the GPS Location of the Emulator.” After you have configured the location of your emulator, the Maps application should display your simulated location, as shown in Figure 3.30. Make sure that the location icon (Image) is showing, which is indicative that the location settings have been enabled on the AVD.

Image

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


Image Warning

If you do not see the location icon presented in the status bar, this means that the location is not yet activated and requires configuring within the AVD.


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)
this.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 permission 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 the Android IDE.

Debugging Your Application on Hardware

You have mastered running applications in the emulator. Now let’s put the application on real hardware. This section discusses how to install the application on a Nexus 4 device with Android 4.3. To learn how to install on a different device or different Android version, readhttp://d.android.com/tools/device.html.

Connect an Android device to your computer via USB and relaunch the Debug configuration of the application. Because you chose the Always prompt to pick device Deployment Target Selection Mode for the configuration, you should now see a real Android device listed as an option in the Android Device Chooser (see Figure 3.31).

Image

Figure 3.31 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. To allow USB debugging, go to Settings, Developer Options, and under Debugging, choose USB debugging. A dialog prompt will appear (see Figure 3.32) requesting that USB debugging be allowed. Click OK to allow debugging.

Image

Figure 3.32 Allowing USB debugging.

Once the USB-connected Android device is recognized, you may be prompted with another dialog asking you to confirm the development computer’s RSA key fingerprint. If so, select the option Always allow from this computer and click OK (see Figure 3.33).

Image

Figure 3.33 Remembering the computer’s RSA key fingerprint.

Once enabled, you can tell that the device is actively using a USB debugging connection because a little Android bug-like icon appears in the status bar (Image). Figure 3.34 shows a screenshot of the application running on a real device (in this case, a smartphone running Android 4.3).

Image

Figure 3.34 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.

Summary

This chapter showed you how to add, build, run, and debug Android projects using the Android IDE. You started by installing the sample applications from within the Android IDE. You then began testing your development environment using a sample application from the Android SDK, and then you created a new Android application from scratch using the Android IDE. You also learned how to make some quick modifications to the application, demonstrating some exciting Android features you will learn about in future chapters.

In the next few chapters, you will learn about the tools available for use in developing Android applications and then focus on the finer points about defining your Android application using the application manifest file. You will also learn how to organize your application resources, such as images and strings, for use within your application.

Quiz Questions

1. What are the benefits of choosing the Snapshot feature listed under the Emulation Options section of the AVD creation wizard?

2. What do the e, w, i, v, d letters stand for in relation to the android.util.Log class, for example, Log.e()?

3. What are the Debug breakpoint keyboard shortcuts for Step Into, Step Over, Step Return, and Resume?

4. What is the keyboard shortcut for organizing imports?

5. What is the keyboard shortcut for toggling a breakpoint in the Android IDE?

6. What is the keyboard shortcut for Override/Implement Methods in the Android IDE?

Exercises

1. Create a Nexus 7 AVD using the preconfigured device definitions.

2. Describe the purpose of the Minimum Required SDK, Target SDK, and Compile With options listed in the Android Application Project creation wizard.

3. Found in the Android Application Project creation wizard, describe the difference between a Blank Activity and a Fullscreen Activity.

4. Perform the steps for configuring the Run or Debug configurations of the MyFirstAndroidApp to launch the application on all compatible devices/AVDs when running or debugging. Write down each of the steps taken in order.

5. Create a new Android Application Project with a new Launcher Icon. For the Launcher Icon, increase the padding to 50%, change the Foreground Scaling to Center, give it a shape of Circle, and change the icon’s background color to blue. Perform any other necessary steps required in order to create the application.

6. There are three Navigation Types available when creating a Blank Activity. Create a new Android Application Project for each Navigation Type available to see what each option provides. Perform any other necessary steps required in order to create the application.

References and More Information

Android SDK Reference regarding the application Activity class:

http://d.android.com/reference/android/app/Activity.html

Android SDK Reference regarding the application Log class:

http://d.android.com/reference/android/util/Log.html

Android SDK Reference regarding the application MediaPlayer class:

http://d.android.com/reference/android/media/MediaPlayer.html

Android SDK Reference regarding the application Uri class:

http://d.android.com/reference/android/net/Uri.html

Android SDK Reference regarding the application LocationManager class:

http://d.android.com/reference/android/location/LocationManager.html

Android Tools: “Using Hardware Devices”:

http://d.android.com/tools/device.html

Android Resources: “Common Tasks and How to Do Them in Android”:

http://d.android.com/guide/faq/commontasks.html

Android sample code:

http://d.android.com/tools/samples/index.html