Writing Android Apps - Writing Internet Applications - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part VI: Writing Internet Applications

Hour 24. Writing Android Apps

THIS HOUR’S TO-DO LIST:

Image Learn why Android was created.

Image Create an Android app.

Image Learn how an Android app is structured.

Image Run an app on an emulator.

Image Run an app on an Android phone.

Java’s a general-purpose programming language that can run on a wide variety of platforms. One of those platforms has arisen in recent years to become an enormously successful spark for new Java development.

The Android operating system, which started out on cell phones and has spread to a variety of other devices, exclusively runs programs written in Java.

These programs, called apps, are built on an open source mobile platform that’s completely free for developers to build on. Anyone can write, deploy, and sell Android apps.

During this hour, you learn about how Android came about, what makes it special, and why so many programmers are developing on the platform. You also create an app and run it on an Android phone (if you own one) and an emulator (if you don’t).

Introduction to Android

Android was launched by Google in 2007, two years after it acquired the technology, as part of an industry-wide effort to establish a new mobile phone platform that was nonproprietary and open, unlike the technology that drives RIM BlackBerry and Apple iPhone. Some of the biggest names in mobile phones and technology—Google, Intel, Motorola, Nvidia, Samsung, and other companies—formed the Open Handset Alliance to promote the new platform for mutual benefit.

Google released the Android Software Development Kit (SDK), a free set of tools for developing Android apps. The first phone running Android, the T-Mobile G1, came out in June 2008.

This effort started slowly, but since early 2010 it has exploded and become a genuine rival to iPhone and other mobile platforms. All major phone carriers now offer Android phones. There’s also a growing market for tablet and ebook readers.

Before Android, mobile application development required expensive programming tools and developer programs. The makers of the phone had control over who’d be allowed to create apps for them and whether the apps could be sold to users.

Android tears down that wall.

The open source and nonproprietary nature of Android means that anyone can develop, release, and sell apps. The only cost involved is a nominal fee to submit apps to Google’s marketplace. Everything else is free.

The place to download the Android SDK and find out more about creating programs for the platform is the Android Developer site at http://developer.android.com. You will consult it often as you write your own apps, because it documents every class in Android’s Java class library and serves as an extensive online reference.

Writing Android apps is easier if you’re using an integrated development environment (IDE) that’s equipped to support the Android SDK. The most popular IDE for Android programming is Eclipse, which also is free and open source. An Android Plug-in for Eclipse makes the SDK function seamlessly inside the IDE.

You can use Eclipse to write Android apps, test them in an emulator that acts like an Android phone, and even deploy them on an actual device.

For most of its existence, the Java language has been used to write programs that run in one of three places: a desktop computer, a web server, or a web browser.

Android puts Java everywhere. Your programs can be deployed on millions of phones and other mobile devices.

This fulfills the original design goal of Java back when James Gosling invented the language in the mid 1990s. He was tasked with creating a language that could run everywhere on devices such as phones, smart cards, and appliances.

Java’s developers set aside those dreams when the language became popular first as a means of running interactive web browser programs and then as a general-purpose language.


Caution

This hour is the longest in the book because there’s a lot to cover when getting your start as an Android app developer and future millionaire. It would have been split over two hours if my publisher had not vetoed the prospective title Sams Teach Yourself Java in 25 Hours.


A little less than 20 years later, the Android platform is hosting as many as a billion Java programs around the world, according to one industry estimate.

Android has the potential to be the most pervasive—and lucrative—area of Java programming for years to come.

Creating an Android App

Android apps are ordinary Java programs that use an application framework, a core set of classes and files that all apps have in common. The framework embodies a set of rules for how apps must be structured in order to run properly on Android devices.

To get started writing apps, you must install and configure the Android SDK, the Eclipse IDE, and the Android Plug-in for Eclipse.

If this is your first experience with Android programming, you can find out how to acquire and set up these tools in Appendix D, “Setting Up an Android Development Environment.”

Go ahead and do that. I’ll wait for you here and catch up with some friends on Facebook.

Done? Good.

1. Run the Eclipse IDE, which looks and acts a lot like NetBeans.

2. Choose File, New, Android Application Project. The New Android Application Wizard opens, as shown in Figure 24.1.

Image

FIGURE 24.1 Creating a new Android project in Eclipse.

3. In the Application Name field, enter SalutonMondo. The same name automatically will be entered in the Project Name field.

4. The Package Name field should contain the name of the Java package to which the classes of this app belong. Enter org.cadenhead.android.

5. Every Android project requires a build target. The target represents the oldest version of Android that can run your app. Because each new Android release has enhanced features, your target choice determines which features you can use.

In the Minimum Required SDK and Target SDK drop-downs, choose API 19.

6. Click Next. The wizard asks more questions about the project.

7. Three check boxes should already be selected: Create Custom Launcher Icon, Create Activity, and Create New Project in Workspace. (If not, select them.)

8. Click Next. The wizard asks about the application’s icon.

9. You can accept the defaults for the icon, so click Next. You’re asked about the activity to create.

10. Choose Fullscreen Activity and click Next.

11. An activity is a task the app can accomplish. Enter SalutonActivity in the Activity Name field.

12. Click Finish. The new app is created and a SalutonMondo item appears in the Package Explorer pane.

Exploring a New Android Project

A new Android project consists of about 20 files and folders that always are organized the same way in an Android app. There might be more files you add depending on the capabilities of the app, but these starting files and folders always must be present.

Figure 24.2 shows the Eclipse Package Explorer after a new Android project has been created.

Image

FIGURE 24.2 Viewing the parts of an Android project.

You can use the folder to explore the file and folder structure of the project. The new SalutonMondo app starts out with the following components:

Image /src folder—The root folder for the app’s Java source code.

Image /src/org.cadenhead.android/SalutonActivity.java—The class for the activity that launches by default when the app is run.

Image /gen folder—The folder for generated Java source code you do not edit manually.

Image /gen/org.cadenhead.android/R.java—The automatically generated resource management source code for the app. (Never edit this!)

Image /assets—The folder for file resources that will not be compiled into the app.

Image /res—The folder for application resources such as strings, numbers, layout files, graphics, and animation. There are subfolders for specific resource types: layout, three values folders, and five drawable folders.

Image AndroidManifest.xml—The app’s primary configuration file.

Image default.properties—A build file generated by the Android Plug-in that you should not edit.

Image project.properties—A configuration file for the project that automatically is generated and must not be edited manually.

These files and folders form the application framework. The first thing you undertake as an Android programmer is to learn how to modify the framework so you can discover what each component can accomplish.

There are additional files that are added to the framework to suit specific purposes.

Creating an App

Although you haven’t done anything to it yet, you could successfully run the new Android project. The framework functions as a working app.

Because there’s no fun in that, you will customize the SalutonMondo app to offer the traditional computer programming greeting “Saluton Mondo!”

In Hour 2, “Writing Your First Program,” you displayed the text “Saluton Mondo!” as a string by calling the method System.out.println().

Android apps display strings that have been stored first in a resource file called strings.xml. You can find this file in the /res/values folder.

Use the Package Explorer to navigate to this folder. Double-click strings.xml. A Resources editor opens, as shown in Figure 24.3.

Image

FIGURE 24.3 Editing an Android app’s string resources.

Strings and other resources are given a name and a value, just like a variable in Java. There are three string resources listed in the Resources elements pane: app_name, dummy_button, and dummy_content.

The names of resources follow three rules:

Image They must be all lowercase.

Image They must have no spaces.

Image They must only use the underscore character _ as punctuation.

Click a string in the Resources elements pane. Name and Value text fields appear along with some guidance on how to edit strings.

The app_name string resource was something you chose when running the New Android Project Wizard. The name should match what you gave it earlier, but you can make changes at any time by editing this string.

The dummy_content string contains text to display on the app’s main (and only) screen when it is run. Click the name of this string to bring it up for editing.

In the Value field, enter Saluton Mondo!.


Caution

Although you can edit XML directly, don’t. There’s usually no need to do it when creating resources for an Android app. The exception is when the Eclipse editor doesn’t support something you want to do in defining a resource. This isn’t the case with strings, so it’s better to stick to the Resources editor. You’re more likely to make errors editing the XML files directly.


Resources are stored in XML files. The Resources editor is a simple XML editor. You also can directly edit the XML itself. Click the strings.xml tab at the bottom of the editor to load this file for direct editing. (Refer to Figure 24.3 where this tab is identified.)

Here’s what strings.xml looks like at the moment:

Output

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SalutonMondo</string>
<string name="dummy_button">Dummy Button</string>
<string name="dummy_content">Saluton Mondo!</string>
</resources>

This editor allows everything in the XML file to be edited, even the markup tags. The string element contains a name attribute that identifies the name of the resource. The value is enclosed within the tag as character data.

To go back to the Resources editor, click the Resources tab. Click the Save button in the Eclipse toolbar to save your change to the file strings.xml.

With that modification, you’re almost ready to run the app.

Setting Up an Android Emulator

Before you can build an Android app, you must set its debugging environment. This can be handled within Eclipse. You must set up an Android Virtual Device (AVD) that can run the app on your desktop as an emulator. You also must create the project’s debug configuration. When you’re done, you can build the app and run it in the emulator.

To configure an Android Virtual Device, first click the green Android phone icon in the Eclipse toolbar, which is shown in Figure 24.4.

Image

FIGURE 24.4 Configuring an Android Virtual Device.

This launches the Android Virtual Device Manager, one of the tools in the Android SDK. The emulators that you’ve created are listed to the left. The manager is shown in Figure 24.5.

Image

FIGURE 24.5 Creating a new Android emulator.

To add a new emulator, click New and follow these steps:

1. In the AVD Name field, give it the name SimpleAVD.

2. In the Device field, choose one of the phones, such as Nexus S.

3. In the Target field, you must choose a target version of Android from the drop-down menu. Choose Android 4.4.2 - API Level 19.

4. In the Skin field, choose No Skin.

5. In the Memory Options section, under RAM enter 768. (Larger sizes have caused the emulator to fail to load on some Windows computers.)

6. In the SD Card section, in the Size field, choose a size for the fake SD card. Enter 1024 and choose MiB from the associated drop-down for an SD card that’s 1024MB in size. You must have this much available space on your computer, so choose smaller if you’d prefer not to take up that much space. The minimum size is 9MB.

7. Click OK. The new emulator is created, which might take a little while (no longer than a minute, generally).

You can create as many emulators as you need. They can be customized for different versions of Android and different kinds of displays.

Close the Android Virtual Device Manager to return to the main Eclipse interface.

Creating a Debug Configuration

The last thing required before you can launch the SalutonMondo app is to create a debug configuration in Eclipse. Follow these steps:

1. Choose Run, Debug Configurations. The Debug Configurations window opens.

2. In the left pane, double-click the Android Application item (shown in Figure 24.6). A new entry called New_configuration is created as its subitem. The right pane displays some configuration options for the new item.

Image

FIGURE 24.6 Creating an Android debug configuration.

3. In the right pane, in the Name field, change it to SalutonDebug.

4. Click the Browse button. The Project Selection dialog opens.

5. Choose the project SalutonMondo and click OK.

6. Click the Target tab.

7. Under Deployment Target Selection Mode, choose Automatically Pick Compatible Device (if it isn’t already chosen). A table enables you to select a target AVD.

8. In the table, select the check box for the SimpleAVD emulator.

9. Click Apply to save your changes and then click Close.

Running the App

Now that you have an Android emulator and a debug configuration, you can run your first app. Click SalutonMondo, the top item in the Package Explorer, and then click the bug icon in the Eclipse toolbar.

The Android emulator loads in its own window. This can take a minute or more, so wait patiently as the fake phone boots up. (The emulator loads so slowly it gives you time to ponder a Chinese proverb: “The oxen are slow, but the earth is patient.”)

The app you have installed will appear with an Android icon and the label SalutonMondo. Click the icon to run the app.

The emulator displays “Saluton Mondo!” as the text and title bar of the app, as shown in Figure 24.7. Controls enable the emulator to be used like a phone, but with a mouse instead of your finger. Click the back button to close the app and see how the Android device is emulated.

Image

FIGURE 24.7 Running an app in the Android emulator.

An emulator can do many of the things a real device can do, including connect to the Internet if the computer has an active connection. It also can receive fake phone calls and SMS messages.

Because it’s not a fully functional device, the apps that you develop must be tested on actual Android phones and tablets.

If you can connect an Android phone (or other device) to your computer using a USB cord, you should be able to run the app if the phone is set in debugging mode. Apps developed with the Android SDK only can be deployed on a phone in this mode.

On the phone, enter this mode by choosing Home, Settings, Applications, Development (or Home, Settings, Developer Options). The Development settings are displayed. Choose the USB debugging option.

Next, in Eclipse, follow these steps:

1. Choose Run, Debug Configurations. The Debug Configurations window opens.

2. Click the Target tab in the right-hand pane to bring it to the front.

3. Change Deployment Target Selection Mode to Always Prompt to Pick Device.

4. Click Apply and Close.

Connect your Android phone with the USB cord. An Android bug icon should appear on the bar at the top of the phone’s screen. If you drag this bar down, you should see the message “USB Debugging Connected.”

Back in Eclipse, click the bug icon in the toolbar. The Android Device Chooser dialog opens (see Figure 24.8).

Image

FIGURE 24.8 Deploying an app on an Android phone.

If the Android phone has been detected, it appears in the top table in Figure 24.8 under the Choose a Running Device option.

Select this option, click the device, and click OK. The app runs on the phone as it did on the emulator.

Like the first program you wrote in Java back in Hour 2, the first app you created on Android is exceptionally nonexceptional. The next project is more ambitious.

Designing a Real App

Android apps can exploit all of the device’s functionality, such as SMS messaging, location-based services, and touch input. In this book’s final programming project, you create a real app called Take Me to Your Leader.

This app takes advantage of an Android’s phone capabilities to make a phone call, visit a website, and load a location in Google Maps. The app puts you in touch with the White House via phone, Web, and maps. (If the president of the United States is not your leader, the app can be customized.)

To get started, you create a new project in Eclipse by performing these steps:

1. Click File, New, Android Application Project. The New Android Application wizard opens.

2. In the Application Name field, enter Leader. This also will enter automatically in the Project Name field.

3. In the Package Name field, enter org.cadenhead.android.

4. In the Minimum Required SDK and Target SDK drop-downs, choose API 19, and then click Next to see more project options.

5. Make sure these three check boxes are selected: Create Custom Launcher Icon, Create Activity, and Create Project in Workspace.

6. Click Next to see questions about the application’s icons.

7. Click Next to accept these defaults.

8. Choose Fullscreen Activity; then click Next.

9. In the Activity Name field, enter LeaderActivity.

10. Click Finish.


Tip

This project covers a lot of ground. As you work through it, you’ll find it handy to keep a browser open to the Android Developer site’s reference section at http://developer.android.com/reference. You can search for the Java classes in the Android class library and the filenames of the files in the project to learn more.


The project appears in the Eclipse Package Explorer, as does the SalutonMondo project. To avoid confusion, you should close SalutonMondo before proceeding. Right-click SalutonMondo in the Package Explorer; then choose Close Project from the pop-up menu.

Organizing Resources

Creating an Android app requires Java programming, but a lot of the work is done in the Eclipse interface. When you are fully versed in the capabilities of the Android SDK, you can accomplish a great deal without writing a single line of Java code.

One thing you do without programming is create resources that will be used by the app. Every new Android project starts out with several folders where resources are placed. To see these folders, expand the Leader folder in the Package Explorer, and then expand the /res folder and all its subfolders (as shown in Figure 24.9).

Image

FIGURE 24.9 Examining an app’s resource folders.

Resources consist of graphics in the PNG, JPG, or GIF format; strings stored in a file called strings.xml; user interface layout files in XML format; and other files you can create. Two others are colors.xml for colors used in the app and styles.xml to define the appearance of user interface components.

The /res folder of a new project contains folders called drawable-hdpi, drawable-ldpi, drawable-mdpi, drawable-xhpdi, and drawable-xxhpdi that have different versions of ic_launcher.png, the app’s icon. The icon’s the small graphic used to launch the app.

The multiple versions of ic_launcher.png are the same graphic sized for different-resolution displays. You won’t be using these icons, so it’s okay to delete them: Click one of the ic_launcher.png files in Package Explorer, and then hit the Delete key. You’ll be asked to confirm each deletion.

Deleting these files causes two red X’s to appear in Package Explorer: one over AndroidManifest.xml and another over the top-level Leader item (which are identified in Figure 24.10). These X’s indicate that the app now has errors that will prevent it from being compiled and run.

Image

FIGURE 24.10 Detecting and fixing errors in the app.

The errors cropped up because the app now lacks an icon. A new graphics file, appicon.png, will be added to the project and designated as its icon in the file AndroidManifest.xml, the app’s main configuration file.

This book’s website contains appicon.png and four other graphics files needed by this app: browser.png, maps.png, phone.png, and whitehouse.png. Visit www.java24hours.com and go to the Hour 24 page for this edition of the book. Download all five files and save them in a temporary folder on your computer.


Caution

Resources are identified in an app using an ID formed from their filename with the extension removed. appicon.png has the ID appicon, browser.png has the ID browser, and so on. No two resources can have the same ID (with the exception of the same graphic being stored at different resolutions in the drawable-* folders, because they count as a single resource).

If two resources have the same name without the extension, such as appicon.png and appicon.gif, Eclipse will flag the error and the app won’t compile.

Resources also must have names that contain only lowercase letters, numbers, underscores (_), and periods (.). The files in this project follow these rules.


Android’s support for multiple resolutions is handy, but it’s not necessary here. Instead of using the existing drawable folders, you will create a new one by following these steps:

1. Click the /res folder in Package Explorer to select it.

2. Choose File, New, Folder. The New Folder dialog opens.

3. Enter drawable in the Folder Name field.

4. Click Finish.

A new folder called drawable will be created inside /res. All of the graphics needed by the app can be stored here without consideration of their resolution.

Files can be added to resources using drag and drop. Open the temporary folder containing the five files, select them, and drag them to the drawable folder in Package Explorer. (You might be asked whether you want to copy the files or copy a link to them. Choose the Copy Files option.)

Now that the project has a new icon, you can set it as the app’s icon and get rid of the errors noted in Package Explorer. This will be handled by editing AndroidManifest.xml.

Configuring the App’s Manifest File

The primary configuration tool in an Android app is a file called AndroidManifest.xml in the main app folder. All XML files utilized by an app can be edited manually or by using the built-in editor in Eclipse. The latter is easier and less error prone. Unless you’re extremely comfortable editing XML, you should stick to the editor until you’ve gained more experience as an Android programmer.

To choose the proper icon for the app, do the following:

1. Double-click AndroidManifest.xml in Package Explorer. The file opens for editing in the main Eclipse window using the built-in editor.

2. Several tabs run along the bottom edge of the editor. Click the Application tab to see settings related to the app (see Figure 24.11).

Image

FIGURE 24.11 Editing the app’s AndroidManifest.xml file.

3. The Icon field identifies the app’s icon, which currently has the incorrect value @drawable/ic_launcher. Click the Browse button next to this field. A Resource Chooser dialog appears listing the five graphical resources you recently added to the app.

4. Choose appicon and click OK. The Icon field now has the correct value.

5. Save the file: Click the Save button in the main Eclipse toolbar or choose File, Save.

The red X’s disappear from the Package Explorer, indicating that the app now has a properly designated icon.

Designing a User Interface

An app’s graphical user interface consists of layouts, which are containers that hold widgets such as text fields, buttons, graphics, and custom widgets of your own design. Each screen displayed to a user can have one layout or multiple layouts contained within each other. There are layouts to stack components vertically or horizontally, organize them in a table, and other arrangements.

An app can be as simple as a single screen or contain multiple screens. A game could be organized into these screens:

Image A splash screen that displays as the game is loading

Image A main menu screen with buttons to view the other screens

Image A help screen explaining how to play

Image A scores screen that lists the highest player scores

Image A credits screen naming the game’s developers

Image A game screen for actual play

The Leader app consists of a single screen, which holds buttons for contacting the president of the United States or a leader to be named later.

All of an app’s screens are kept in the /res/layout folder. This project has an activity_leader.xml file in this folder that’s designated as the screen to display when the app loads.

To begin editing this screen’s layout, double-click activity_leader.xml in Package Explorer. The screen opens in the main Eclipse window, as shown in Figure 24.12.

Image

FIGURE 24.12 Editing an activity’s graphical user interface.

The editing window includes a Palette pane with several folders that can be expanded. The Form Widgets subpane, which is likely to be expanded, displays some simple widgets. These can be dragged and dropped onto the screen at right.

Follow these steps to add three graphical buttons to the screen:

1. Delete the textview widget that displays the “Dummy Button” text. Click this widget on the screen and press the Delete key.

2. Click the Layouts folder in the Palette pane. The subpane expands.

3. Drag the LinearLayout (vertical) widget from the palette to the screen. Two new buttons appear above the screen window, and one of them is selected: Set Horizontal Orientation. Dragging the layout onto the screen determines how user interface elements placed on it will be arranged.

4. Click the Images & Media folder in the Palette pane. The subpane expands.

5. Drag an ImageButton widget from the Palette to the screen. A Resource Chooser button opens, asking you to choose an image to display on the button. Choose phone and click OK. The button now has a graphic of a phone.

6. Drag another ImageButton widget and drop it to the right of the phone button. Choose the browser resource for this one. A browser button is added.

7. Drag one more ImageButton widget and drop it to the right of browser, assigning it the maps resource.

8. An Outline pane lists the widgets on the screen. Select the imageButton1 item. The properties of the button open in the Properties pane (see Figure 24.13).

Image

FIGURE 24.13 Customizing a widget’s properties.

9. Scroll down the Properties pane until you see an ID property. Its value currently is set to @+id/imageButton1. Change this to @+id/phonebutton. A dialog asks whether to update all references to reflect this change. Click Yes.

10. In the On Click property, enter the value processClicks. (This will be explained in the next section.)

11. Repeat steps 8–10 for imageButton2, giving it the ID @+id/webbutton and the On Click property processClicks.

12. Repeat steps 8–10 for imageButton3, giving it the ID @+id/mapbutton and the On Click property processClicks.

13. Click the LinearLayout item in the Outline. The properties for the screen appear in the Properties pane.

14. Click the value for Background; then click the ... button. The Reference Chooser opens.

15. Expand Drawable, choose whitehouse, and click OK. A graphic of the White House becomes the screen’s background.

16. Click the Save button.

The finished screen is shown in Figure 24.14.

Image

FIGURE 24.14 Previewing an app’s graphical user interface.

Writing Java Code

At this point, you’ve done the bulk of the work on the new app, but you haven’t written a single line of Java code. App development is easier when you utilize as many capabilities of the Android SDK as possible without resorting to programming.

Apps are organized into Activities, which represent things an app can do. Each Activity is defined by its own Java class. When you created this app, you specified that an Activity named LeaderActivity should be created. A class matching this name runs automatically when the app is loaded.

The source code for LeaderActivity.java can be found in Package Explorer in the /src/org.cadenhead.android folder. Double-click this file to edit it.

When you start, the class has a lot of existing source code.

Like all Activities, the LeaderActivity class is a subclass of Activity in the android.app package, which contains the behavior necessary to display a screen, collect user input, save user preferences, and so on.

The onCreate() method defined in the class is called when the class is loaded.


Note

You can open the R.java file for viewing in the /res/gen/org.cadenhead.android folder to learn more about why the main resource is referred to as R.layout.main. The R class is generated automatically by the Android SDK to enable resources to be referenced by their IDs. You never should edit this class yourself.


The first thing the method does is use super() to call the same method in its superclass:

super.onCreate(savedInstanceState);

Next, it calls setContentView(), a method that selects the screen that will be displayed. The argument to this method is an instance variable, R.layout.activity_leader, that refers to the file activity_leader.xml in /res/layout. As you may recall, the ID of a resource is its filename without the extension.

When you designed the app’s user interface earlier, you set the On Click property of each button to processClicks. This indicated that a method called processClicks() would be called when a user clicked a widget on the screen.

Now it’s time to implement that method. Add these statements to LeaderActivity above the onCreate() method:

public void processClicks(View display) {
Intent action;
int id = display.getId();
}

This method is called with one argument: a View object from the android.view package. A View is a visual display of some kind in an app. In this case, it’s the screen containing the Dialer, Browser, and Maps buttons.

The View object’s getId() method returns the ID of the button that was clicked: phonebutton, webbutton, or mapbutton.

This ID is stored in the id variable so it can be used in a switch statement to take action based on the click:

switch (id) {
case (R.id.phonebutton):
// ...
break;
case (R.id.webbutton):
// ...
break;
case (R.id.mapbutton):
// ...
break;
default:
break;
}

This code will take one of three actions, using the integer of each ID as the conditional in the switch.

The first statement in the processClicks() method creates a variable to hold an Intent object, a class in Android’s android.content package:

Intent action;

Intents in Android are how Activities tell another Activity what to do. They’re also the way an app communicates with the Android device.

Here are the three Intents employed in this method:

action = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:202-456-1111"));

action = new Intent(Intent.ACTION_VIEW, Uri.parse("http://whitehouse.gov"));

action = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=White House, Washington, DC"));

The Intent() constructor takes two arguments:

Image The action to take, represented by one of its class variables

Image The data associated with the action

These three Intents tell the Android device to set up an outgoing phone call to the White House public phone line at (202) 456-1111, visit the website http://whitehouse.gov, and load Google Maps with the partial address “White House, Washington, DC,” respectively.

After you have created an Intent, the following statement makes it do something:

startActivity(action);

Because you deleted the Dummy Button on the activity, you must remove this line of code, which is the last one in the onCreate() method:

findViewById(R.id.dummy_button).setOnTouchListener (mDelayHideTouchListener);

An easy way to remove it is to put // in front of it, turning it into a comment that’s ignored by the compiler.

The following import statements must be added to the class for the code you’ve added to function properly:

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

The full text of the processClicks() method in LeaderActivity class is shown in Listing 24.1. Make sure your code matches the listing.

LISTING 24.1 The Full Text of LeaderActivity.java


1: public void processClicks(View display) {
2: Intent action;
3: int id = display.getId();
4: switch (id) {
5: case (R.id.phonebutton):
6: Log.i(TAG, "Making call");
7: action = new Intent(Intent.ACTION_DIAL,
8: Uri.parse("tel:202-456-1111"));
9: startActivity(action);
10: break;
11: case (R.id.webbutton):
12: Log.i(TAG, "Loading browser");
13: action = new Intent(Intent.ACTION_VIEW,
14: Uri.parse("http://whitehouse.gov"));
15: startActivity(action);
16: break;
17: case (R.id.mapbutton):
18: Log.i(TAG, "Loading map");
19: action = new Intent(Intent.ACTION_VIEW,
20: Uri.parse("geo:0,0?q=White House, Washington, DC"));
21: startActivity(action);
22: break;
23: default:
24: break;
25: }
26: }


Save the file when you’re done. It should compile successfully (something Eclipse does automatically). If not, the familiar red X’s appear in the Package Explorer, identifying the files in the project where the errors were found.

When there are no errors, you’re almost ready to run the app.

You must create a new debug configuration for the project first:

1. Click the arrow next to the Debug button in the main Eclipse toolbar; then choose Debug Configurations. The Debug Configurations dialog opens.

2. Double-click Android Application in the left pane. A new configuration called New_configuration (1) is created.

3. Enter LeaderDebug as the Name.

4. Click the Browse button, choose the project Leader, and click OK.

5. Click the Target tab to bring it to the front.

6. With Automatic selected as the Deployment Target Selection Mode, select the SimpleAVD Android Virtual Device.

7. Change Deployment Target Selection Mode to Always Prompt to Pick Device, click Apply, and then click Close.

A new debug configuration called LeaderDebug is created.

To run the app, click the arrow next to the Debug button and choose LeaderDebug (if it is present). If not, choose Debug Configurations, choose LeaderDebug, and click Debug. The Android Device Chooser opens. Select Launch a New Android Virtual Device, select SimpleAVD, and click OK.

The emulator loads over the next few minutes and then automatically runs the app.

An emulator does not emulate everything an Android device can do. The Leader app’s Dialer and Browser buttons should work properly, but you might encounter problems with Maps.

The app also can be run on an Android phone, if you have one working with the Android SDK and the phone has been set to debugging mode.

Click the arrow next to Debug and choose LeaderDebug, which definitely should be present this time. Select Choose a Running Android Device, select your phone in the list, and then click OK.

Figure 24.15 shows the app running on my phone. When the phone is shifted from portrait mode to landscape mode, the app shifts accordingly. (The figure also shows that I have 141 new voicemail messages. I probably should check those.)

Image

FIGURE 24.15 Take me to your leader!

The Leader app also has been added to the phone’s applications with its own “Take Me to Your Leader” icon. It will stay on the phone even after you disconnect the USB cable.

Congratulations! The world now has one billion and one Android apps.


Note

As you might have surmised, there’s a lot more to Android programming than can be covered in a single hour. Sams offers another book that takes the Java programming you’ve learned here and extends it with another 24 hours of Android-specific coverage: Sams Teach Yourself Android Application Development, Third Edition, by Carmen Delessio, Lauren Darcey, and Shane Conder (ISBN 978-0-672-33444-3). This hour was written to be fully compatible with how that book covers Android.


Summary

The goal of Sams Teach Yourself Java in 24 Hours has been to help you become comfortable with the concepts of programming and confident in your ability to write your own applications, whether they run on a desktop computer, web page, web server, or even a phone. Java has an approach that is somewhat difficult to master. (Feel free to scratch out the word somewhat in the previous sentence if it’s a gross misstatement of the truth.)

As you build experience in Java, you’re building experience that grows increasingly relevant, because concepts such as object-oriented programming, virtual machines, and secure environments are on the leading edge of software development.

If you haven’t already, you should check out the appendices for additional useful information.

At the conclusion of this hour, you can explore Java in several places. Programmers are discussing the language on the weblogs at http://weblogs.java.net. Numerous Java job openings are displayed in the database of employment websites such as www.careerbuilder.com. There’s also a website for this book at www.java24hours.com where you can send email to the author and read answers to reader questions, clarifications to the book, and (gulp) corrections.

One way to continue building your skills as a Java programmer is to read Sams Teach Yourself Java in 21 Days. I wrote that book also, and it expands on the subjects covered here and introduces new ones, such as JDBC, Java servlets, and network programming.

There’s also more coverage of Android.

If you didn’t skip ahead and have just completed all 24 hours, kudos. Please use your newfound programming skills to get a great job and rebuild the world economy.

Workshop

Q&A

Q. Why is Eclipse used to create Android apps instead of NetBeans?

A. You can use NetBeans to develop apps, but it’s a more cumbersome and less well-supported IDE for Android programming. Eclipse has been designated by Google as the preferred Android IDE. The official documentation and tutorials on the Android Developer site athttp://developer.android.com all use Eclipse.

Most programming books for Android also employ Eclipse. Although there’s a learning curve required to switch from NetBeans to Eclipse when you dive into Android, after you master the basics of writing, debugging, and deploying an app, you should find Eclipse easier to use because it’s so much better supported by Android programmers and technical writers.

Q. Why do so many movies have the same exact sound of a man screaming in anguish?

A. That sound is the Wilhelm scream, a sound effect that was heard first in the 1951 movie Distant Drums. It turns up most often when somebody falls from a great height, is shot by a gun, or is knocked back by an explosion. Two famous uses are in the original Star Wars, when a stormtrooper is shot by Luke Skywalker and falls off a ledge, and in the animated movie Toy Story when Sheriff Woody knocks Buzz Lightyear out the window.

The sound was popularized by movie sound designer Ben Burtt, who found it in a Warner Brothers stock library when developing sound for Star Wars and included it in every Steven Spielberg and George Lucas movie he worked on. It has since become a tradition among sound designers and can be heard in more than 140 movies.

The voice actor who screamed is believed to be Sheb Wooley, an actor and singer who recorded the 1958 novelty song “Purple People Eater.”

The scream being named Wilhelm comes from the third movie to use the sound effect. In the 1953 film The Charge at Feather River, Private Wilhelm yells in anguish as he’s shot by an arrow.

Quiz

If you would like to dial up the knowledge you’ve just acquired in Android development, answer the following questions.

1. Which of the following companies was not part of the Open Handset Initiative, the group that championed Android?

A. Google

B. Apple

C. Motorola

2. What object is used for one Activity to tell another Activity what to do?

A. An Intent

B. An Action

C. A View

3. Which of the following tasks can an Android emulator not perform?

A. Receiving an SMS message

B. Connecting to the Internet

C. Making a phone call

Answers

1. B. Apple, because Android was created in part as an open source, nonproprietary alternative to the Apple iPhone.

2. A. An Intent also is the way an Activity communicates with the Android device.

3. C. Emulators can’t do everything an actual device can do, so they’re only part of the testing process for apps.

Activities

To make your Android knowledge go for longer distance, undertake the following activities:

Image Change the text of the SalutonMondo app to “Hello, Android” and run the app in the emulator and on an Android device (if one is available to you).

Image Create a new version of Take Me to Your Leader for a different world leader, customizing the phone, Web, and map destinations.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.