Building Your First Android Application Android

Now it’s time to write your first Android application. You start with a simple Hello World project and build upon it to explore some of the features of Android.

The Android emulator launching (locked).

The Android emulator launching (locked)

The Snake game.

The Snake game.

Creating and Configuring a New Android Project

You can create a new Android project 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 (with the letter a and a plus sign), on the Eclipse toolbar.
  2. Choose a Project Name. In this case, name the project MyFirstAndroidApp.
  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 checkbox or change the directory to wherever you want to store the source files.
  4. Select a build target for your application. Choose a target that is compatible with the Android handsets you have in your possession. For this example, you might use the Android 2.2 target.
  5. 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, but you are free to choose your own
    com.androidbook.myfirstandroidapp package name.
  7. Check the Create Activity checkbox. This instructs the wizard to create a default launch activity for the application. Call this Activity class. My First Android App Activity
  8. Your project settings should look like Figure.

  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 are used to define the functionality of the application. The following files are created by default with a new Android application.

Configuring My First Android App using the Android Project Wizard.

Configuring My First Android App using the Android Project Wizard.

There are a number of other files saved on disk as part of the Eclipse project in the workspace. However, the files included in Table 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).

Important Android Project Files and Directories

Important Android Project Files and Directories

Creating Launch Configurations 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 My First Android App 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 MyFirstAn- droidApp 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 My First Android App 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 (the little green circle with the play button and a drop-down arrow).
  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 start a new emulator instance, and check the box next to the AVD you created, as shown in Figure.
  4. Manually choosing a target selection mode.

    Manually choosing a target selection mode

  5. The Android emulator starts up, which might take a moment.
  6. Press the Menu button to unlock the emulator.
  7. The application starts, as shown in Figure.
  8. Click the Home button in the Emulator to end the application.
  9. Pull up the Application Drawer to see installed applications. Your screen looks something like Figure.
  10. Click on the My First Android Application icon to launch the application again.

My First Android App running in the emulator.

My First Android App running in the emulator

My First Android App application icon in the Drawer.

My First Android App application icon in the Drawer

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 file MyFirstAndroidApp.java and create a new method called forceError() in your class and make a call to this method in your onCreate() method.

The forceError() method forces a new unhandled error in your application.

The forceError() method should look something like this:

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.

Shut down the application and the emulator. 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 (the little green bug with the drop-down arrow) .
  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 launch the emulator again, unlocking it if needed.

It takes a moment for the emulator to start up and for the debugger to attach. If this is the first time you’ve debugged an Android application, you need to click through some dialog boxes, such as the one shown in Figure, the first time your application attaches to the debugger.

My First Android App crashing gracefully.

My First Android App crashing gracefully

Switching debug perspectives for Android emulator debugging.

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.

Debugging My First Android App in Eclipse.

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 on the left side of the line of code and choosing Toggle Breakpoint (or Ctrl+Shift+B).

In the emulator, restart your application and step through your code. You see My First Android App has thrown the exception and then the exception shows up in the Variable Browser pane of the Debug Perspective. Expanding the variables 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 phone, such as system_process and com.android.phone. If you launch MyFirstAndroidApp, you see com. androidbook .myfirs tandroid app show up as a process on the emulator listing. Force the app to close because it crashes, and you 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.

Adding Logging Support to Your Android Application

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

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:

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

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.

A Filtered LogCat log for My First Android App.

A Filtered 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.

Important MediaPlayer and URI Parsing Methods

Important MediaPlayer and URI Parsing Methods

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

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

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 theoperation should fail for some reason, the method logs a custom error with your logging tag.

The playMusicFromWeb() method should look something like this:

And finally, you want to cleanly exit when the application shuts down.To do this, you need to override the onStop() method and stop the MediaPlayer object and release its resources.

The onStop() method should look something like this:

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, 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.

Creating an AVD with Google APIs

To have some fun with location-based services and maps integration, you should use some of the Google applications often available on Android handsets—most notably, the Google Maps application. Therefore, you must create another AVD. This AVD should have exactly the same settings as the Android_Vanilla2.2 AVD, with one exception: Its Target should be the Google APIs equivalent for that API level (which is 8).You can call this AVD Android_ with_ GoogleAPIs_2.2.

Configuring the Location of the Emulator

After you have created a new AVD with the Google APIs support, you need to shut down the emulator you’ve been running. Then debug the My First Android App application again, this time choosing the new AVD.

The emulator does not have location sensors, so the first thing you need to do is seed your emulator with GPS coordinates. To do this, launch your emulator in debug mode with an AVD supporting the Google Maps add-ins and follow these steps:

In the Emulator:

  1. Press the Home key to return to the Home screen.
  2. Launch the Maps application from the Application drawer.
  3. Click the Menu button.
  4. Choose the My Location menu item. (It looks like a target.)
  5. In Eclipse:

  6. Click the DDMS perspective in the top-right corner of Eclipse.
  7. You see an Emulator Control pane on the left side of the screen. Scroll down to the Location Control.
  8. Manually enter the longitude and latitude of your location. (Note they are in reverse order.)
  9. Click Send.

Back in the emulator, notice that the Google Map now shows the location you seeded. Your screen should now display your location as Yosemite Valley, as shown in Figure.

Your emulator now has a simulated location.

Finding the Last Known Location

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

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 phone 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:

Setting the location of the emulator to Yosemite Valley.

Setting the location of the emulator to Yosemite Valley

Finally, your application requires special permissions to access location-based functionality. You must register this permission in your Android Manifest.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 Android Manifest .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 attribute, as shown here:

If you forget to set the debuggable attribute to true, the handset shows the dialog for waiting for the debugger to connect until you choose Force Close and update the manifest file.

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.

Android Device Chooser with USB-connected Android handset.

Android Device Chooser with USB-connected Android handset

Choose the Android Device as your target, and you see that the My First Android App application gets loaded onto the Android handset and launched, just as before. Provided you have enabled the development debugging options on the handset, you can debug the application here as well. You can tell the handset is actively using a USB debugging connection, because there is a little Android bug-like icon in the notification bar. A screenshot of the application running on a real handset is shown in Figure.

My First Android App running on Android device hardware.

My First Android App running on Android device hardware.

Debugging on the handset 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.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Android Topics