Chapter 3. Using the Android Development Environment for Real Applications

MicroJobs: This Book’s Main Sample Application

We want to take a look at applications that are more complex than “Hello, Android,” and that’s what we’ll do in this chapter. Based on the theory that it’s often easiest to explain things through an example, we’ll take an in-depth look at a more complex application, called MicroJobs. Some of the application’s code modules are named MJAndroid, so we’ll also use that name for the code associated with MicroJobs.

We’ll first take a look at what we want the MicroJobs application to do, then we’ll quickly get into the code itself. After looking at the structure of the application, we’ll describe in detail how to build the application and how to get it running on the emulator. Finally, we’ll take a look at some helpful debug hints in case you’re developing a similar application and it doesn’t start up. The reasons are not always obvious in the Android environment.

Android and Social Networking

One of the great promises of Android mobile phones is their ability to run applications that enhance opportunities for social networking between users. This promise echoes the reality of the Internet. The first generation of Internet applications were about user access to information, and many of those applications have been very popular. The second wave of Internet applications has been about connecting users to each other. Applications such as Facebook, YouTube, and many others enhance our ability to connect with people of similar interests, and allow the application’s users to provide some or all of the content that makes the application what it is. Android has the potential to take that concept and add a new dimension: mobility. It’s expected that a whole new generation of applications will be built for users of mobile devices: social networking applications that are easy to use while walking down the street; applications that are aware of the user’s location; applications that allow the easy sharing of content-rich information, such as pictures and videos.

As mentioned in the previous chapter, we are going to study just such an application as an example of Android application development. The code is available for you to download from the book’s website (http://www.oreilly.com/catalog/9780596521479), and is based on an actual entry in the first round of the Android Developer Challenge, sponsored by Google. The application is an example of a class of applications known as “friend finders” because that’s the central idea.

In the case of the MicroJobs application, instead of finding friends, the user is trying to locate a temporary job in the vicinity, so she can work for a few hours and make some money. The premise is that employers looking for temporary help have entered available jobs, descriptions, hours, and offered wages in a web-based database that is accessible from Android mobile phones. Anyone looking for a few hours’ work can use the MicroJobs application to access that database, look for jobs in the immediate area, communicate with friends about potential employers and potential jobs, and call the employer directly if she is interested in the position. For our purposes here, we won’t create an online service; we’ll just have some canned data on the phone. The application has a number of features that extend that central idea in ways that are unique to mobile handsets:

Mapping

The Android mobile phone environment provides very rich support for dynamic, interactive maps, and we’re going to take full advantage of its capabilities. You’ll see that with very little code, we’ll be able to show dynamic maps of our local neighborhood, getting location updates from the internal GPS to automatically scroll the map as we move. We’ll be able to scroll the map in two directions, zoom in and out, and even switch to satellite views.

Finding friends and events

A graphic overlay on the map will show us where jobs are placed in the area, and will allow us to get more information about a job by just touching its symbol on the map. We will access Android’s Contact Manager application to get address information for our friends (telephone numbers, instant messaging addresses, etc.), and access the MicroJobs database to get more information about posted jobs.

Instant messaging

When we find friends we want to chat with, we will be able to contact them via instant messages (IMs), by trading SMS messages with our friends’ mobile phones.

Talking with friends or employers

If IMing is too slow or cumbersome, we’ll be able to easily place a cellular call to our friends, or call the employer offering a job.

Browsing the Web

Most employers have an associated website that provides more detailed information. We’ll be able to select an employer off a list or off the map and quickly zero in on their website to find out, for example, what the place looks like.

This is a fun application that could easily be developed further into a full-blown service, but our intent in this book is to show you just how easy it is to develop and combine these powerful capabilities in your own application. The complete source code for the application is available to you on the book’s website, and we will refer to it frequently throughout this book. Although it’s not absolutely required in order to understand the material in the book, you are strongly encouraged to download the source to your own computer. That way, you’ll have it readily available for reference, and it will be easy to copy sections of code and paste them into your own applications as you move on.

Figure 3-1 shows the screen displayed by MJAndroid when you first run it. It’s a map of your local area, overlaid with a few buttons and pins.

MJAndroid opening screenshot
Figure 3-1. MJAndroid opening screenshot

Downloading the MJAndroid Code

The MJAndroid application source code and project files are available from the O’Reilly website, at http://www.oreilly.com/catalog/9780596521479. To download it to your development system, use a browser to navigate to the link given, and select “Download MJAndroid.” Your operating system (Windows, Linux, or OS X) will ask you to confirm that you want the download to happen, and ask you where to put the downloaded files. It doesn’t matter where you put the downloaded, compressed files, but you want to extract the uncompressed files into the directory that Eclipse uses as your default workspace, to make it easy to load the project. The default place is a folder called workspace under the eclipse directory that you created when you installed Eclipse. If you can’t remember where that is, start Eclipse, go to File → Switch Workspace, and it will display the location of the current workspace directory. Expand the compressed files into that directory, and be sure “use directories” is checked in the decompression dialog, so the correct folders will be created and the files written to them.

To import the MJAndroid project into Eclipse, go to File → Import..., and you’ll see a Select dialog list of possible import types. Click on “Existing Projects into Workspace,” and use the Browse button to find the directory where you just expanded MJAndroid. Eclipse will import the project, and it should appear in the Project Explorer pane.

A Brief Tour of the MJAndroid Code

MJAndroid is a relatively simple application, despite the capabilities it gives its users. This section will give you an overview of the code and resource modules, tell you where they are located in the directory structure, and provide a glimpse of what each component does. You may want to refer to this section in the future when you’re trying to find example code for a particular function and want to locate it in the MJAndroid code tree. MJAndroid uses a directory structure that is derived directly from the standard Android application directory structure, so this will also serve as a guide to finding code in other application source trees.

The Project Root Folder (MJAndroid)

If you use Eclipse’s Package Explorer to look at the MJAndroid project, you will see a set of folders and files. It turns out all of these were originally created by Eclipse and the Android Development Tool, and similar folders and files are created for any Android application. Let’s see what they do:

src folder

src is short for Source, and this is where Eclipse and ADT expect to find all of the Java source files in your application. Almost all of the work you do to create an Android application is done in this folder and the res folder. In the next section, we will take a more detailed look at how the src folder is structured for MJAndroid.

Android Library

This is just what it says: a pointer to the library of Android class files that Eclipse links to in order to provide the Android APIs. You don’t need to do anything with this entry, but if you ever need to confirm that a particular Android class is (still) there, this is where you would look.

assets folder

This folder is useful for holding assets that are used by the application: fonts, external JAR files, and so on. For this book and MJAndroid, we don’t have any assets, so we will not be using the assets folder.

doc folder

Short for documentation, this is where you can put documentation for a project. For MJAndroid, web pages that describe the Loco project are stored in this folder.

res folder

res is short for resources, and this is where Eclipse and ADT expect to find the resources for your application. Resources include most of the XML files that define the layout of your application, any image files (icons, pictures that are used in your layout, sprites, etc.)—just about everything that isn’t part of a Java source file.

AndroidManifest.xml file

This file is created by ADT when you create a new Android project. As the extension suggests, it is an XML file, and it contains a wealth of information about your application: what the activities, services, and intents are, which one starts first, which permissions your application needs from the operating system (for restricted functions such as getting location or making a phone call), and a lot of other information. This file is so important that ADT provides a special editor to maintain it. It’s just an XML file, so you could always edit it with a text editor, but you will see later that the specialized editor makes everything a lot easier.

Eclipse also creates two other files and another directory at the same directory level (the root directory of the MJAndroid project) that are not shown by Package Explorer. The .classpath file is used by Eclipse to keep track of the location of standard Java classes and libraries. Eclipse uses the .project file to store information about the project. You will never need to touch either of these files directly, so Eclipse doesn’t bother you with them in Package Explorer. The bin directory is where Eclipse puts the compiled class files for each of your Java source files (the ones in src). You can see all of these files if you list the directory of the root folder, but you don’t really need to pay any attention to them, because Eclipse will do it all for you.

The Source Folder (src)

The package name for MJAndroid is com.microjobsinc.mjandroid. Eclipse lays out the equivalent directory structure, just as it would for any Java project, and shows you the whole thing when you open src. In addition to these package folders, there is a folder named for the package that contains all the Java files for the project. These include:

MicroJobs.java

The main source file for the application. It designates the Activity that starts first, displays the map that is the centerpiece of the application, and calls other Activities or Services as necessary to implement different features in the user interface.

MicroJobsDatabase.java

A database helper that provides easy access to the local MJAndroid database. This is where all the employer, user, and job information is stored, using SQLite.

AddJob.java and EditJob.java

Part of the database portion of MJAndroid. These provide screens through which the user can add or edit job entries in the database.

MicroJobsDetail.java

The Activity that displays all of the detail information about a particular job opportunity.

MicroJobsEmpDetail.java

The Activity that displays information about an employer, including name, address, reputation, email address, phone number, etc.

MicroJobsList.java

The Activity that displays a list of jobs (as opposed to the map view in MicroJobs.java). It shows a simple list containing Employer and Job entries, and allows the user to sort the list by either field and call up specifics of the job or employer by touching the name on the list.

R.java

This file is created automatically by Eclipse and the ADT to contain Java references for all the resources that are defined in the res folder (see the next section). You should never have to edit this file by hand, as it is maintained for you as you add or edit resources. Take a look, though, just to see how resources are defined for later use in the other Java source files.

The Resource Folder (res)

The res folder contains three folders, and another pointer to the same AndroidManifest.xml file that shows up in the root directory:

drawable

As you might suspect, this contains all the drawable images that MJAndroid will use: any JPEG or PNG or GIF files or bitmaps.

layout

As with many modern application environments, Android allows you to separate what is displayed by an Activity from how it is displayed. This directory contains XML files that describe the “how”; in other words, they are the layout files for each Activity in the application. When a program runs, Android applies the rules in these files to create the visible layout, a process known as “inflating.”

values

Good programming practice calls for the separation of data that does not directly affect the operation of an application, making it a lot easier to do things like translation to foreign languages, theming, etc. We aren’t going to be super strict about this in MJAndroid, but we will at least put all of the obvious user-visible text into a file called strings.xml. You’ll see how easy it is to retrieve these for use in the actual Android Activity source code.

First Steps: Building and Running the MicroJobs Application

So now that we know a bit about which files are located in which folders, what happens when we ask Android to run the MJAndroid application? And for that matter, how do we ask Android to run the application? Let’s take a closer look at the Android SDK environment and the views and commands available to us for running and debugging any application.

A Very Short Tour of the Android SDK/Eclipse IDE

The Android SDK provides three “perspectives” for working with Android projects and applications. If you’re new to Eclipse, a perspective is a collection of Eclipse views that provides a particular viewpoint of an application. Eclipse and the Android SDK have preassembled sets of views that developers have found useful, and you can switch between those views, either by selecting one from the Window menu or by using the icons in the upper-right corner of the Eclipse window. You are also free to customize the perspectives, but in this book we will assume you use the standard ones provided:

Java

This is the default perspective, launched by Eclipse when you first say that you want to view the workspace. It includes:

Package Explorer

Used for viewing folders and selecting files

Source Editor

Used for editing Java and XML source files

Tabbed Views

Contains a set of useful views, accessed by tabs:

  • Problems, which lists errors that Eclipse and the Android SDK find in the application

  • Javadoc, which extracts and displays Javadoc documentation from the application

  • Declaration, which makes it easy to find the declaration for any variable in the code

  • Console, which shows the console terminal output from either the emulator or the Android phone

  • Search, which is used to search for results

  • Progress, which displays progress as an application is launched and runs

Debug

This perspective is primarily for debugging the application, obviously. If you select Debug from the Run menu, Eclipse switches automatically to this perspective, providing you with views that are useful for debugging:

Debug

A view of the application call stack, showing you how you got to the current debug point

Source View

This shows you the current source location in the running (or stopped) application

Console and Tasks Views

This contains the console terminal (as in the Java perspective), and a window where development tasks can be recorded and tracked

Variables, Breakpoints, and Expressions

This is where you can view current variable values, view breakpoints, and evaluate expressions while debugging

Outline

This shows you an outline of the current activity being executed: the classes declared, and the instances and methods defined

DDMS

This perspective, which stands for Dalvik Debug Monitor Service, is unique to Android. It provides Android-specific debug information, including:

Devices

This shows you what devices (emulated or hardware) are available to run your applications.

Emulator Control

This is where you can adjust parameters that define how the telephony and location emulators work. When running on the emulator, we’ll use this to manually send location updates to the location provider.

LogCat

This is a view of the very powerful logging facility available under Android, which allows you to see everything going on in the target system, and to filter out the information you really care about.

Threads, Heap, and File Explorer

This is a tabbed set of views where you can follow the running threads in the application, see how the heap is being used, and select files from the folder hierarchy.

Loading and Starting the Application

Running MJAndroid from the SDK is complicated by the fact that the application uses a MapView. Android requires a special Map API Keywhenever you use a MapView, and the key is tied to your particular development machine. You’ll learn all about this in Chapter 7, but right now the easiest way for you to run MJAndroid is simply to install the .apk file in the emulator.

You are probably already in the Java perspective, but if not, select it now. If you loaded the MJAndroid application into your Eclipse workspace folder as described earlier, you should see it in the Package Explorer. If you now right-click on the MJAndroid entry, you get a long menu of options. Select Open Project, a little over halfway down the list, and Eclipse will open the MJAndroid project and allow you to see its contents.

If we didn’t have to deal with the Map API Key issue, starting the application would be as easy as selecting Run from the menu of the same name. Eclipse shows a dialog box (labeled “Run As”) that asks how you want to run the application. You will always select Android Application from the top of the list.

At this point, the Android SDK will either select the target hardware you identified or start the emulator as the target. It will automatically load your application on the target and attempt to start it. In the case of MJAndroid, you should see the opening screen, shown earlier in Figure 3-1.

Digging a Little Deeper: What Can Go Wrong?

As you are developing your application, at some point you will try to run it, as just described, and it won’t work. You’ll either get an unexpected result or you’ll get an error on the target screen that may be less than informative. Let’s spend a little time looking at what the Android SDK does to get an application running, and what might go wrong.

As you know, Android applications run under a virtual machine called Dalvik. When you selected “Run” in the previous section, tools in the Android SDK saw that there was not a compiled version of MJAndroid available to run. They first took all the layout and variable information that was coded into XML files and converted it into Java source code (in the R.java folder), and then compiled all the Java source code into Java bytecode files (.class files). A translator converted the Java bytecodes into Dalvik bytecode files (.dex files). The Dalvik modules were combined with other information about the application, including the manifest file AndroidManifest.xml, and packaged into an Android package (or .apk) file. In the case of the MJAndroid application, this file is MJAndroid.apk, located in .../MJAndroid/bin. An Android package is what the target receives to load and start the application running. A lot of the startup information is in the AndroidManifest.xml file, so let’s take a closer look at it.

When you double-click the AndroidManifest.xml listing in the Package Explorer, the Android SDK starts the Android Manifest editor in the middle pane of the Java perspective, and loads the file, as shown in Figure 3-2.

Android Manifest editor
Figure 3-2. Android Manifest editor

As you see, there are five tabs at the bottom of the editor pane, which give you five different views of the manifest file:

Overview

This is the view presented by default (if the file hasn’t been opened before). It shows the package name for the application and shared user ID information (for use when multiple applications have to share a common user ID), presents some options for exporting and signing your application, and provides links to each of the tabs described next.

Application

This view provides access to a lot of the parameters that can be set for an application. Most of these are either self-explanatory or are not used in an application like MJAndroid. Two areas of interest are:

  • Icon, which tells Android where to find a drawable icon to use for the application on the target.

  • Application Nodes, which identifies the activities, services, and providers in the application. There are a number of things worth noting in this section.

    Uses Library

    For MJAndroid, we will use the MapActivity to display maps. That class is not part of the core Android libraries, so we call out here that we need access to the additional library com.google.android.maps.

    Activity Attributes

    Click on the little triangle to the left of MicroJobs (Activity) to see the intent filters attached to that activity. If you recall, activities in Android are run when their intent filters satisfy an intent that was expressed by some already running application. In this case we see two filters for MicroJobs:

    <action android:name="android.intent.action.MAIN" />

    This tells the Android application launcher that this activity is the one to be started first for MJAndroid.

    <category android:name="android.intent.category.LAUNCHER" />

    This tells Android that the icon for this activity and application is to be displayed on the menu of launchable applications.

    We’ll talk about the intent filters assigned to the other activities as we get to their use in the code.

Permissions

Android controls what applications are allowed to do by requiring that they ask for permission to perform critical actions. When the application is installed on a real device, the user can choose whether to allow the requested permissions and proceed with installation, or to reject installation (in the emulator environment, it is assumed all permission requests are granted). It is important to include only the permissions needed by your application; you don’t want to ask the user for permissions that you don’t need. For MJAndroid, we’ll need the permissions shown in this tab:

  • <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> allows us to use fine-grained location providers, such as GPS.

  • <uses-permissionandroid:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> allows us to access additional location commands.

  • <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> allows the creation of mock location providers.

  • <uses-permission android:name="android.permission.INTERNET" /> allows us to access the Internet.

  • <uses-permission android:name="android.permission.CALL_PHONE" /> allows the application to place telephone calls.

Instrumentation

Android allows developers to replace Dalvik classes with substitute classes when running in the emulator environment. The intent is to allow one to better instrument particularly tricky code. We won’t be using this feature in this book, but you can search for “Instrumentation” in the Android documentation to find out more.

AndroidManifest.xml

This view shows the actual XML file that results from all the choices made in the other views. If you are already comfortable with XML, you may prefer to edit the file directly in this view, rather than using the others. Be careful, though, because Android is very choosy about seeing the right tags in the right places, and doesn’t always give you an error message indicating what, exactly, is wrong. The editor used in this view does XML syntax checking for you, but it doesn’t know anything about the semantics of the various XML tags defined by Android. It’s interesting to make changes in the other views and see their effect on the actual XML file by looking at this view.

So there is a lot of information in the AndroidManifest.xml file, and the system uses that information when launching the application. In the next chapter, we’ll see what actually goes on inside the application as it starts up.

Running an Application on the T-Mobile Phone

Emulators are great development timesavers, and the QEMU emulator used by Android runs particularly well. You can probably debug 95% of your application just using the emulator. But an Android application doesn’t have much raison d’être until it gets the chance to run on real phones. Luckily, Android makes it easy for you to try your application on one. As this is written, the T-Mobile G1 phone is the only Android phone on the market, so we’ll give instructions for using it with the Android SDK. Future Android phones should be similar.

Enable USB debugging on your phone

Before you connect your T-Mobile G1 to the host, go to the Desktop screen on the phone, and push the Menu button. One of the menu options is Settings. Touch it to select, and you will be taken to the Settings dialog for the phone, which consists of a list of things you can set. The list is bigger than the screen, so scroll up and down until you find Applications, and touch that entry. You’re taken to a sublist related to applications, and one of the entries is Development. Touch that, and you’re shown two options:

USB Debugging

You want to enable this option by touching it. A green checkmark should appear in the adjacent checkbox.

Stay awake

This option will keep the screen on as long as the USB cable is connected. It can be annoying when the screen goes off, taking you back to the opening screen, so you might as well enable this too.

Your T-Mobile G1 now expects to receive debug information through the USB port, but don’t plug it in just yet, because we may need to load a special driver on the host.

Load the USB driver for ADB

Depending on which host operating system you are using, you will need to install a driver for the USB port, or configure the existing driver:

Windows (either Vista or XP)

You will need to install a USB driver that is included with the Android SDK. The driver is located in <SDK>/usb_driver, where <SDK> is the location in which you installed the Android SDK.

Once you’ve extracted the driver, plug in the USB cable connecting the phone to the host. A Found New Hardware dialog will pop up that gives you a chance to load the new driver. The details will vary slightly, but in general:

  1. Windows will ask if you want to search for a driver, which you don’t. Instead, you want to tell it where you put the driver directory, so select the option that is something like “Install from a list or specified location.”

  2. Ignore any dire warnings from Windows about the driver not being certified. This just means that no one paid Microsoft to perform the certification tests.

  3. When asked for the driver’s location, browse to the USB driver directory, <SDK>usb_driver. The extraction should have created a subdirectory called android_usb_windows. Select that subdirectory and click OK.

Windows will load the driver and tell you that the hardware is ready to use.

Mac OS X

You’re all set without doing anything.

Ubuntu Linux

For Ubuntu, you need to configure the USB connection with a rules file, located at /etc/udev/rules.d/50-android.rules. The contents of the rules file are slightly different depending on which version of Ubuntu you are using. If you are using a different Linux distribution, you’ll need to look at its documentation to understand how USB rules files are configured.

Ubuntu Dapper Drake

Create a file at /etc/udev/rules.d/50-android.rules with one line in it:

SUBSYSTEM=="usb_device", SYSFS{idVendor}=="0bb4", MODE="0666"
Ubuntu Gutsy Gibbon or Hardy Heron

Create a file at /etc/udev/rules.d/50-android.rules with one line it it:

SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"
In all cases (Dapper, Gutsy, or Hardy), make the rules file readable and executable by executing from the shell as root:
chmod a+rx /etc/udev/rules.d/50-android.rules

Connecting the phone

Now that you have the driver loaded, you are ready to plug in the USB cable that connects the T-Mobile G1 to the host. The phone will beep, and Eclipse will update itself as it learns of the new target. If you go to a terminal (Linux or OS X) or Command window (Windows) and type adb devices, you should see something like this:

>adb devices
List of devices attached
emulator-5554   device
HT840GZ12968    device

Running MicroJobs on the phone

Now when you select Run from the Eclipse menu, you will still get the dialog that asks what kind of application you want to run (Android Application, Java Applet, Java Application, etc.), but now you will get a second dialog that asks which target you want to run on. The available targets will be listed, and you can click on either the emulator or the phone, depending on which you’d prefer. Select the phone, and the application is downloaded (using the debug signature; more about application signatures in Chapter 7), and started on the phone. Most of the debug features available on the emulator (covered in detail in Chapter 5) are also available when running in debug mode on the phone.

Summary

We’ve looked at this more realistic application in some detail to understand the procedures you’ll need to follow when developing your own application. Your application is likely to differ in the details, but it will inherit a similar structure, and you will use similar procedures to build and run your application, both on the emulator and on a live phone. You now know all the basics you need to start building your application, but as you’ll see, there is a lot more to learn about Android and the features you can build into your application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.200.94.150