[Android Software Development] michael.the.don:
[Ultimate Guide][Part 2-1/09/2011]Android App Development - From Scrap

PART II

All you need to start writing your own Android applications is a copy of the Android SDK and the Java development kit. Unless you’re a masochist, you’ll probably want a Java IDE — Eclipse is particularly well supported — to make development a little easier.

Versions of the SDK, Java, and Eclipse are available for Windows, Mac OS, and Linux, so you can explore Android from the comfort of whatever OS you favor. The SDK includes an emulator for all three OS environments, and because Android applications are run on a virtual machine, there’s no advantage to developing from any particular operating system.

Android code is written using Java syntax, and the core Android libraries include most of the features from the core Java APIs. Before they can be run, though, your projects are first translated into Dalvik byte code. As a result, you get the benefits of using Java, while your applications have the advantage of running on a virtual machine optimized for Android devices.

The SDK download includes all the Android libraries, full documentation, and excellent sample applications. It also includes tools to help you write and debug your applications, like the Android Emulator to run your projects and the Dalvik Debug Monitoring Service (DDMS) to help debug them.

Needed

Because Android applications run within the Dalvik virtual machine, you can write them on any platform that supports the developer tools. This currently includes the following:

❑ Microsoft Windows (XP or Vista)

❑ Mac OS X 10.4.8 or later (Intel chips only)

❑ Linux

To get started, you’ll need to download and install the following:

❑ The Android SDK

❑ Java Development Kit (JDK) 5 or 6

You can download the latest JDK from Sun at

http://java.sun.com/javase/downloads/index.jsp

If you already have a JDK installed, make sure that it meets the version requirements listed above, and

note that the Java runtime environment (JRE) is not sufficient

.

Downloading and Installing the SDK

The Android SDK is completely open. There’s no cost to download and use the API, and Google doesn’t charge to allow distribution of your finished programs. You can download the latest version of the SDK for your development platform from the Android development home page at-

http://code.google.com/android/download.html

The SDK is presented as a ZIP fi le containing the API libraries, developer tools, documentation, and several sample applications and API demos that highlight the use of particular API features. Install it by unzipping the SDK into a new folder. (Take note of this location, as you’ll need it later.) The examples and step-by-step instructions provided are targeted at developers using Eclipse with the Android Developer Tool (ADT) plug-in. Neither is required, though — you can use any text editor or Java IDE you’re comfortable with and use the developer tools in the SDK to compile, test, and debug the code snippets and sample applications.

If you’re planning to use them, the next sections explain how to set up Eclipse and the ADT plug-in as your Android development environment. Later in the chapter, we’ll also take a closer look at the developer tools that come with the SDK, so if you’d prefer to develop without using Eclipse or the ADT plugin, you’ll particularly want to check that out.

Developing with Eclipse

Using Eclipse with the ADT plug-in for your Android development offers some significant advantages. Eclipse is an open source IDE (integrated development environment) particularly popular for Java development. It’s available to download for each of the development platforms supported by Android (Windows, Mac OS, and Linux) from the Eclipse foundation homepage:

www.eclipse.org/downloads/

There are many variations available when selecting your Eclipse download; the following is the recommended configuration for Android:

❑ Eclipse 3.3, 3.4 (Ganymede)

❑ Eclipse JDT plug-in

❑ WST

WST and the JDT plug-in are included in most Eclipse IDE packages.

Installing Eclipse consists of uncompressing the download into a new folder. When that’s done, run the Eclipse executable. When it starts for the first time, create a new workspace for your Android development.

Using the Eclipse Plug-in

The ADT plug-in for Eclipse simplifies your Android development by integrating the developer tools, including the emulator and .class-to-.dex converter, directly into the IDE. While you don’t have to use the ADT plug-in, it does make creating, testing, and debugging your applications faster and easier.

The ADT plug-in integrates the following into Eclipse:

❑ An Android Project Wizard that simplifi es creating new projects and includes a basic application template

❑ Forms-based manifest, layout, and resource editors to help create, edit, and validate your XML resources

❑ Automated building of Android projects, conversion to Android executables (.dex), packaging to package fi les (.apk), and installation of packages onto Dalvik virtual machines

❑ The Android Emulator, including control of the emulator’s appearance, network connection settings, and the ability to simulate incoming calls and SMS messages

❑ The Dalvik Debug Monitoring Service (DDMS), which includes port forwarding; stack, heap, and thread viewing; process details; and screen capture facilities

❑ Access to the device or emulator’s fi lesystem, allowing you to navigate the folder tree and transfer files

❑ Runtime debugging, so you can set breakpoints and view call stacks

❑ All Android/Dalvik log and console outputs

Installing the ADT Plug-in

Install the developer tools plug-in by the following steps:

1. Select Help ➪ Software Updates ➪ Find and Install … from within Eclipse.

2. In the resulting dialog box, choose Search for new features to install.

3. Select New Remote Site, and enter the following address into the dialog box, and enter-

https://dl-ssl.google.com/android/eclipse/

4. The new site you entered should now be checked. Click Finish.

5. Eclipse will now download the plug-in. When it’s fi nished, select Android Plugin ➪ Developer Tools from the resulting Search Results dialog box, and click Next.

6. Read and then Accept the terms of the license agreement, and click Next and then Finish. As the ADT plug-in is not signed, you’ll be prompted before the installation continues.

7. When complete, you’ll have to restart Eclipse and update the ADT preferences. Restart and select Window ➪ Preferences … (or Eclipse ➪ Preferences for the Mac OS).

8. Then select Android from the left panel.

9. Click Browse …, and navigate to the folder into which you unzipped the Android SDK, then click Apply and OK.

If u have an installation error of org.eclipse.wst.sse.ui. then insatall software from the following-

Eclipse 3.6 (Helios):http://download.eclipse.org/releases/helios

Eclipse 3.5 (Galileo):http://download.eclipse.org/releases/galileo

Eclipse 3.4 (Ganymede):http://download.eclipse.org/releases/ganymede/

Updating the Plug-in

As the Android SDK matures, there are likely to be frequent updates to the ADT plug-in. In most cases, to update your plug-in, you simply:

1. Navigate to Help ➪ Software Updates ➪ Find and Install …

2. Select Search for updates of the currently installed features, and click Finish …

3. If there are any ADT updates available, they will be presented. Simply select them and choose Install.

Sometimes a plug-in upgrade is so significant that the dynamic update mechanism can’t be used. In those cases, you may have to remove the previous plug-in completely before installing the newer version as described in the previous section.

Starting a new project

To create a new Android project using the Android New Project Wizard:

1. Select File ➪ New ➪ Project.

2. Select the Android Project application type from the Android folder, and click Finish.

3. In the dialog that appears, enter the details for your new project. The “Project name” is the name of your project fi le; the “Package name” specifies its package; the “Activity name” is the name of the class that is your initial Activity; and the “Application name” is the friendly name for your application.

4. When you’ve entered the details, click Finish.

The ADT plug-in then creates a new project that includes a new class that extends Activity. Rather than being completely empty, the default template implements “Hello World.” Before modifying the project, take this opportunity to configure run and debug launch configurations.

Creating a Launch Configuration

Launch configurations let you specify runtime options for running and debugging applications. Using

a launch configuration you can specify the following:

❑ The Project and Activity to launch

❑ The emulator options to use

❑ Input/output settings (including console defaults)

You can specify different launch configurations for Run and Debug modes. The following steps show how to create a launch configuration for an Android application:

1. Select Run ➪ Open Run Dialog … (or Run ➪ Open Debug Dialog …).

2. Right-click Android Application on the project type list, and select New.

3. Enter a name for the configuration. You can create multiple configurations for each project, so create a descriptive title that will help you identify this particular setup.

4. Now choose your start-up options. The first (Android) tab lets you select the project and Activity that you want to start when you run (or debug) the application.

5. Use the Target tab to configure the emulator. There are options to choose the screen size, device skin, and network connection settings. You can also optionally wipe the user data on the emulator and enable or disable the start-up animation. Using the command-line textbox, you can specify additional emulator start-up options if needed.

6. Finally, set any additional properties in the Common tab.

7. Click Apply, and your launch configuration will be saved

Running and Debugging Your Android Applications

You’ve created your first project and created the run and debug configurations for it. Before making any changes, test your installation and configurations by running and debugging the Hello World project. From the Run menu, select Run or Debug to launch the most recently selected configuration, or select Open Run Dialog … or Open Debug Dialog … to select a configuration to use.

If you’re using the ADT plug-in, running or debugging your application:

❑ Compiles the current project and converts it to an Android executable (.dex).

❑ Packages the executable and external resources into an Android package (.apk).

❑ Starts the emulator (if it’s not already running).

❑ Installs your application onto the emulator.

❑ Starts your application.

If you’re debugging, the Eclipse debugger will then be attached, allowing you to set breakpoints and debug your code.

Understanding the app

With that confirmed, let’s take a step back and have a real look at your first Android application. Activity is the base class for the visual, interactive components of your application; it is roughly equivalent to a Form in traditional desktop development. The following snippet shows the skeleton code for an Activity-based class; note that it extends Activity, overriding the onCreate method.

package com.paad.helloworld;

import android.app.Activity;

import android.os.Bundle;

public class HelloWorld extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

}

}

What’s missing from this template is the layout of the visual interface. In Android, visual components are called Views, which are similar to controls in traditional desktop development.

In the Hello World template created by the wizard, the onCreate method is overridden to call setContentView, which lays out the user interface by inflating a layout resource, as highlighted below:

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

}

The resources for an Android project are stored in the res folder of your project hierarchy, which includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML resources to provide design time access to them through the R variable.

The following code snippet shows the UI layout defined in the main.xml fi le created by the Android project template:

<?xml version=”1.0” encoding=”utf-8”?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:orientation=”vertical”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”>

<TextView

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=”Hello World, HelloWorld”

/>

</LinearLayout>

Defining your UI in XML and inflating it is the preferred way of implementing your user interfaces, as it neatly decouples your application logic from your UI design. To get access to your UI elements in code, you add identifier attributes to them in the XML definition. You can then use the findViewById method to return a reference to each named item. The following XML snippet shows an ID attribute added to the TextView widget in the Hello World template:

<TextView

android:id=”@+id/myTextView”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=”Hello World, HelloWorld”

/>

And the following snippet shows how to get access to it in code:

TextView myTextView = (TextView)findViewById(R.id.myTextView);

Alternatively, if you need to, you can create your layout directly in code as shown below:

public void onCreate(Bundle icicle)

{

super.onCreate(icicle);

LinearLayout.LayoutParams lp;

lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,

LayoutParams.FILL_PARENT);

LinearLayout.LayoutParams textViewLP;

textViewLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,

LayoutParams.WRAP_CONTENT);

LinearLayout ll = new LinearLayout(this);

ll.setOrientation(LinearLayout.VERTICAL);

TextView myTextView = new TextView(this);

myTextView.setText(“Hello World, HelloWorld”);

ll.addView(myTextView, textViewLP);

this.addContentView(ll, lp);

}

All the properties available in code can be set with attributes in the XML layout. As well as allowing easier substitution of layout designs and individual UI elements, keeping the visual design decoupled from the application code helps keep the code more concise.

Types of Android Applications

Most of the applications you create in Android will fall into one of the following categories:

❑ Foreground Activity An application that’s only useful when it’s in the foreground and is effectively suspended when it’s not visible.

❑ Background Service An application with limited interaction that, apart from when being configured, spends most of its lifetime hidden.

❑ Intermittent Activity Expects some interactivity but does most of its work in the background. Often these applications will be set up and then run silently, notifying users when appropriate.

Complex applications are difficult to pigeonhole into a single category and include elements of all three. When creating your application, you need to consider how it’s likely to be used and then design it accordingly. Let’s look more closely at some of the design considerations for each application type described above.

Foreground Activities

When creating foreground applications, you need to consider the Activity life cycle carefully so that the Activity switches seamlessly between the foreground and the background. Applications have no control over their life cycles, and a backgrounded application, with no Services,is a prime candidate for cleanup by Android’s resource management. This means that you need to save the state of the application when the Activity becomes invisible, and present the exact same state when

it returns to the foreground.

Background Services

These applications run silently in the background with very little user input. They often listen for messages or actions caused by the hardware, system, or other applications, rather than rely on user interaction. It’s possible to create completely invisible services, but in practice, it’s better form to provide at least some sort of user control. At a minimum, you should let users confirm that the service is running and let them configure, pause, or terminate it as needed.

Intermittent Activities

Often you’ll want to create an application that reacts to user input but is still useful when it’s not the active foreground Activity. These applications are generally a union of a visible controller Activity with an invisible background Service.

These applications need to be aware of their state when interacting with the user. This might mean updating the Activity UI when it’s visible and sending notifications to keep the user updated when it’s in the background.

Android Development Tools

The Android SDK includes several tools and utilities to help you create, test, and debug your projects. For more detail than is included here, check out the Android documentation at:

http://code.google.com/android/intro/tools.html

As mentioned earlier, the ADT plug-in conveniently incorporates most of these tools into the Eclipse IDE, where you can access them from the DDMS perspective, including:

❑ The Android Emulator An implementation of the Android virtual machine designed to run on your development computer. You can use the emulator to test and debug your android applications.

❑ Dalvik Debug Monitoring Service (DDMS) Use the DDMS perspective to monitor and control the Dalvik virtual machines on which you’re debugging your applications.

❑ Android Asset Packaging Tool (AAPT) Constructs the distributable Android package files (.apk).

❑ Android Debug Bridge (ADB) The ADB is a client-server application that provides a link to a running emulator. It lets you copy files, install compiled application packages (.apk), and run shell commands.

The following additional tools are also available:

❑ SQLite3 A database tool that you can use to access the SQLite database fi les created and used by Android

❑ Traceview Graphical analysis tool for viewing the trace logs from your Android application

❑ MkSDCard Creates an SDCard disk image that can be used by the emulator to simulate an external storage card.

❑ dx Converts Java .class bytecode into Android .dex bytecode.

❑ activityCreator Script that builds Ant build fi les that you can then use to compile your Android applications without the ADT plug-in

The Android Emulator

The emulator is the perfect tool for testing and debugging your applications, particularly if you don’t have a real device (or don’t want to risk it) for experimentation. The emulator is an implementation of the Dalvik virtual machine, making it as valid a platform for running

Android applications as any Android phone. Because it’s decoupled from any particular hardware, it’s an excellent baseline to use for testing your applications. A number of alternative user interfaces are available to represent different hardware configurations, each with different screen sizes, resolutions, orientations, and hardware features to simulate a variety

of mobile device types. Full network connectivity is provided along with the ability to tweak the Internet connection speed and

latency while debugging your applications.

The ADT plug-in integrates the emulator into Eclipse so that it’s launched automatically when you run or debug your projects. If you aren’t using the plug-in or want to use the emulator outside of Eclipse, you can telnet into the emulator and control it from its console.

Dalvik Debug Monitor Service (DDMS)

The emulator lets you see how your application will look, behave, and interact, but to really see what’s happening under the surface, you need the DDMS. The Dalvik Debug Monitoring Service is a powerful debugging tool that lets you interrogate active processes, view the stack and heap, watch and pause active threads, and explore the file system of any active emulator. The DDMS perspective in Eclipse also provides simplified access to screen captures of the emulator and the logs generated by LogCat.

If you’re using the ADT plug-in, the DDMS is fully integrated into Eclipse and is available from the DDMS perspective. If you aren’t using the plug-in or Eclipse, you can run DDMS from the command line, and it will automatically connect to any emulator that’s running.

The Android Debug Bridge (ADB)

The Android debug bridge (ADB) is a client-service application that lets you connect with an Android Emulator or device. It’s made up of three components: a daemon running on the emulator, a service that runs on your development hardware, and client applications (like the DDMS) that communicate with the daemon through the service.

As a communications conduit between your development hardware and the Android device/emulator, the ADB lets you install applications, push and pull files, and run shell commands on the target device. Using the device shell, you can change logging settings, and query or modify SQLite databases available on the device.

The ADT tool automates and simplifies a lot of the usual interaction with the ADB, including application installation and update, log files, and file transfer (through the DDMS perspective). To learn more about what you can do with the ADB, check out the documentation at http://code.google.com/android/reference/adb.html.