Getting Started

WHAT'S IN THIS CHAPTER?_

> How to install the Android SDK, create a development environment, and debug your projects.

> Understanding mobile design considerations and the importance of optimizing for speed and efficiency and designing for small screens and mobile data connections.

> Using Android Virtual Devices, the emulator, and developer tools.

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, MacOS, and Linux, so you can explore Android from the comfort of whatever OS you favor. The SDK tools and emulator work on 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 with 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 must first be 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 mobile 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.

By the end of this chapter you'll have downloaded the Android SDK, set up your development environment, completed two new applications, and run and debugged them with the DDMS using the emulator running on an Android Virtual Device.

If you've developed for mobile devices before, you already know that their small-form factor, limited power, and restricted memory create some unique design challenges. Even if you're new to the game,

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

it's obvious that some of the things you can take for granted on the desktop or the Web aren't going to work on a mobile.

As well as the hardware limitations, the user environment brings its own challenges. Mobile devices are used on the move and are often a distraction rather than the focus of attention, so your applications need to be fast, responsive, and easy to learn and use.

This chapter examines some of the best practices for writing mobile applications to help overcome the inherent hardware and environmental challenges. Rather than try to tackle the whole topic, we'll focus on using the Android SDK in a way that's consistent with good mobile design principles.

DEVELOPING FOR ANDROID

The Android SDK includes all the tools and APIs you need to write compelling and powerful mobile applications. The biggest challenge with Android, as with any new development toolkit, is learning the features and limitations of its APIs.

If you have experience in Java development you'll find that the techniques, syntax, and grammar you've been using will translate directly into Android, although some of the specific optimization techniques may seem counterintuitive.

If you don't have experience with Java but have used other object-oriented languages (such as C#), you should find the transition straightforward. The power of Android comes from its APIs, not from Java, so being unfamiliar with all the Java-specific classes won't be a big disadvantage.

What You Need to Begin

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 later)

> 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 or use the API, and Google doesn't charge (or require review) to distribute your finished programs on the Android Market or otherwise.

You can download the latest version of the SDK for your development platform from the Android development homepage at http://developer.android.com/sdk/index.html

Unless otherwise noted, the version of the Android SDK used for ivriting this book ivas version 2.1 rl.

The SDK is presented as a ZIP file containing only the latest version of the Android developer tools. Install it by unzipping the SDK into a new folder. (Take note of this location, as you'll need it later.)

Before you can begin development you need to add at least one SDK Platform; do this on Windows by running the "SDK Setup.exe'' executable, or on MacOS or Linux by running the "android" executable in the tools subfolder. In the screen that appears, select the "Available Packages'' option on the left panel, and then select the SDK Platform versions you wish to install in the "Sources, Packages, and Archives'' panel on the right. The selected platform will then be downloaded to your SDK installation folder and will contain the API libraries, documentation, and several sample applications.

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 plug-in you'll particularly want to check that out.

The examples included in the SDK are well documented and are an excellent source for full, working examples of applications written for Android. Once you've finished setting up your development environment it's worth going through them.

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 for download for each of the development platforms supported by Android (Windows, MacOS, and Linux) from the Eclipse foundation homepage: www.eclipse.org/downloads/

There are many variations available; the following is the recommended configuration for Android:

> Eclipse JDT plug-in

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

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

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

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 simplifies 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 files (.apk), and installation of packages onto Dalvik virtual machines

> The Android Virtual Device manager, which lets you create and manage virtual devices hosting emulators that run a specific release of the Android OS and with set memory constraints

> The Android Emulator, including control of the emulator's appearance and 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 file system, enabling 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

Figure 2-1 shows the DDMS perspective within Eclipse with the ADT plug-in installed.

Installing the ADT Plug-In

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

1. Select Help O Install New Software... from within Eclipse.

2. In the resulting dialog box enter the following address into the Work With text entry box and press Enter: https://dl-ssl.google.com/android/eclipse/

3. Eclipse will now search for the ADT plug-in. When finished it will display the available plugin, as shown in Figure 2-2. Select it by clicking the checkbox next to the Developer Tools root node, and click Next.

4. Eclipse will now download the plug-in. When it's finished, ensure both the Android DDMS and Android Developer Tools plug-ins are selected and click Next.

FIGURE 2-1

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

6. When installation is complete you'll have to restart Eclipse and update the ADT preferences. Restart and select Window O Preferences... (or Eclipse O Preferences for MacOS).

7. Then select Android from the left panel.

8. Click Browse... and navigate to the folder into which you unzipped the Android SDK; then click Apply. The list will then update to display each of the available SDK targets, as in Figure 2-3. Click OK to complete the SDK installation.

If you download a new version of the SDK and place it in a different location, you will need to update this preference to reflect the SDK with which the ADT should be building.

FIGURE 2-2

_ Preferences type fllterteKt

General Android Ant help

Install/Update Java

Run''Debug

Tasks

Team

Usage Data Collector

Validation

Android

Android Preferences

SDK Location: C:\AndroidSDKiandroid-sdti_1709T_windows

Note: The list of SDK Targets below is only reloaded once you hit Apply' or OK',

Target Name

Vendor

Platform

API-

Android 11

Android Open Source Proiect

11

2

Android 1.5

Android Open Source Project

1.5

3

Android 2.0

Android Open Source Project

2.0

5

Google APIs

Google Inc.

1.5

Apply

FIGURE 2-3

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 O Check for Updates.

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

Sometimes a plug-in upgrade may be 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.

Creating Your First Android Application

You've downloaded the SDK, installed Eclipse, and plugged in the plug-in. You're now ready to start programming for Android. Start by creating a new project and setting up your Eclipse run and debug configurations.

Starting a New Android Project

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

1. Select File O New O Project.

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

3. In the dialog that appears (shown in Figure 2-4), enter the details for your new project. The "Project name'' is the name of your project file; the "Package name'' specifies its java package; Create Activity lets you specify the name of a class that will be your initial Activity; and the "Application name'' is the friendly name for your application. "Min SDK Version'' lets you specify the minimum version of the SDK that your application will run on.

Selecting the minimum SDK version requires you to choose between gaining functionality provided in newer SDK releases and making your application available to a larger group of Android devices. Your application will be available from the Google Android Market on any device running the specified build or higher.

Android version 1.6 (Donut) is version 4 —at the time of going to print, the majority of Android devices were currently running at least version 4. The 2.0 (Eclair) SDK is version 5, while 2.1 is version 7.

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

FIGURE 2-4

If you selected Create Activity the ADT plug-in will create a new project that includes a class that extends Activity. Rather than being completely empty, the default template implements Hello World. Before modifying the project, take this opportunity to configure launch configurations for running and debugging.

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 virtual device and emulator options to use

> Input/output settings (including console defaults)

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

You can specify different launch configurations for running and debugging applications. The following steps show how to create a launch configuration for an Android application:

Select Run Configurations... or Debug Configurations... from the Run menu.

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

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.

FIGURE 2-5

Now choose your start-up options. The first

(Android) tab lets you select the project to run and the Activity that you want to start when you run (or debug) the application. Figure 2-5 shows the settings for the project you created earlier.

Use the Target tab shown in Figure 2-6 to select the default virtual device to launch on, or select manual to select a device or AVD each time. You can also configure the emulator's network connection settings and optionally wipe the user data and disable the boot animation when launching a virtual device. Using the command line textbox you can specify additional emulator start-up options if needed.

FIGURE 2-6

The Android SDK does not include a default virtual machine. Yon will need to create a virtual machine before you can run or debug your applications using the emulator. If the virtual device selection dialog in Figure 2-6 is empty, click Manage... to open the SDK and Virtual Machine Manager and create one. The SDK and Virtual Machine Manager is described in more detail later in this chapter.

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 Run Configurations... or Debug Configurations... to select a specific configuration to use.

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

> 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 selected virtual device (if you've selected an AVD and it's not already running)

> Installs your application onto the target device

> Starts your application

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

If everything is working correctly you'll see a new Activity running in the emulator, as shown in Figure 2-7.

Understanding Hello World

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. Listing 2-1 shows the skeleton code for an Activity-based class; note that it extends Activity, overriding the onCreate method.

LISTING 2-1: Hello World package com.paad.helloworld; Available for download on

Wrax.com 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 savedlnstanceState) { super.onCreate(savedlnstanceState);

FIGURE 2-7

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.

The Hello World template created by the wizard overrides the onCreate method to call setContentview, which lays out the user interface by inflating a layout resource, as highlighted below:

©Override public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); 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 resources to provide design-time access to them through the R variable, as described in Chapter 3.

Listing 2-2 shows the UI layout defined in the main.xml file created by the Android project template.

LISTING 2-2: Hello World layout resource

<?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 Text View 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)findViewByld(R.id.myTextView);

Alternatively (although it's not generally considered good practice), you can create your layout directly in code, as shown in Listing 2-3.

LISTING 2-3: Creating layouts in code public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState);

LinearLayout.LayoutParams lp;

lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,

LayoutParams.FILL_PARENT);

Available for download on Wrax.com

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.

You'll learn how to create complex layouts and about the Views used to populate them in Chapter 4.

App Gangster

App Gangster

Get All The Support And Guidance You Need To Be A Success At Dominating Apps. This Book Is One Of The Most Valuable Resources In The World When It Comes To Becoming The Godfather Of Smart Phone Apps.

Get My Free Ebook


Responses

Post a comment