Android applications, like most mobile phone applications, are developed in a host-target development environment. In other words, you develop your application on a host computer (where resources are abundant) and download it to a target mobile phone for testing and ultimate use. Applications can be tested and debugged either on a real Android device or on an emulator. For most developers, using an emulator is easier for initial development and debugging, followed by final testing on real devices.
To write your own Android mobile phone applications, you’ll first need to collect the required tools and set up an appropriate development environment on your PC or Mac. In this chapter we’ll collect the tools you need, download them and install them on your computer, and write a sample application that will let you get the feel of writing and running Android applications on an emulator. Linux, Windows, and OS X are all supported development environments, and we’ll show you how to install the latest set of tools on each. Then, we’ll show you any configuration you need to do after installing the tools (setting PATH environment variables and the like), again for each of the three operating systems. Finally, we’ll write a short little “Hello, Android” application that demonstrates what needs to be done in order to get a generic application running.
The Android SDK supports several different integrated development environments (IDEs). For this book we will focus on Eclipse because it is the IDE that is best integrated with the SDK, and, hey, it’s free. No matter which operating system you are using, you will need essentially the same set of tools:
Since you’re probably going to develop on only one of the host operating systems, skip to the appropriate section that pertains to your selected operating system.
The Android Software Development Kit supports Windows (XP and Vista), Linux (tested on Ubuntu Dapper Drake, but any recent Linux distro should work), and Mac OS X (10.4.8 or later, Intel platform only) as host development environments. Installation of the SDK is substantially the same for any of the operating systems, and most of this description applies equally to all of them. Where the procedure differs, we will clearly tell you what to do for each environment:
Install JDK: The Android SDK requires JDK version 5 or version 6. If you already have one of those installed, skip to the next step. In particular, Mac OS X comes with the JDK version 5 already installed, and many Linux distributions include a JDK. If the JDK is not installed, go to http://java.sun.com/javase/downloads and you’ll see a list of Java products to download. You want JDK 6 Update n for your operating system, where n is 6 at the time of this writing.
Select the distribution for “Windows Offline Installation, Multi-language.”
Read, review, and accept Sun’s license for the JDK. (The license has become very permissive, but if you have a problem with it, alternative free JDKs exist.)
Once the download is complete, a dialog box will ask you whether you want to run the downloaded executable. When you select “Run,” the Windows Installer will start up and lead you through a dialog to install the JDK on your PC.
Select the distribution for “Linux self-extracting file.”
Read, review, and accept Sun’s license for the JDK. (The license has become very permissive, but if you have a problem with it, alternative free JDKs exist.)
You will need to download the self-extracting
binary to the location in which you want to install
the JDK on your filesystem. If that is a system-wide
directory (such as /usr/local), you will need
root access. After the file is downloaded, make
it executable (chmod +x
jdk-6
version
-linux-i586.bin
),
and execute it. It will self-extract to create a tree
of directories.
Mac OS X comes with JDK version 5 already loaded.
Install Eclipse: The Android SDK requires Eclipse version 3.3 or later. If you do not have that version of Eclipse installed yet, you will need to go to http://www.eclipse.org/downloads to get it, and you might as well get version 3.4 (also known as Ganymede), since that package includes the required plug-ins mentioned in the next step. You want the version of the Eclipse IDE labeled “Eclipse IDE for Java Developers,” and obviously you want the version for your operating system. Eclipse will ask you to select a mirror site, and will then start the download.
The Eclipse download comes as a big ZIP file that you install by extracting the files to your favorite directory. For this book, we’ll assume that you extracted to C:/eclipse. Eclipse is now installed, but it will not show up in your Start menu of applications. You may want to create a Windows shortcut for C:/eclipse/eclipse.exe and place it on your desktop, in your Start menu, or someplace else where you can easily find it.
Note that, as of this writing, the version of Eclipse installed if you request it on Ubuntu Hardy Heron is 3.2.2, which does not contain all the plug-ins needed for Android. The Eclipse download comes as a big tarball (.gz file) that you install by extracting the files to your favorite directory. For this book, we’ll assume that you extracted to /usr/lib/eclipse. The executable itself is located in that directory and is named eclipse.
Check for required plug-ins: You can skip this step if you just downloaded a current version of Eclipse as we recommended. If you are using a preinstalled version of Eclipse, you need to make sure you have the Java Development Tool (JDT) and Web Standard Tools (WST) plug-ins. You can easily check to see whether they are installed by starting Eclipse and selecting menu options “Windows → Preferences...”. The list of preferences should include one for “Java” and one for either “XML” or “Web and XML.” If they aren’t on the list, the easiest thing to do is reinstall Eclipse, as described in the previous step. Installing “Eclipse IDE for Java Developers” will automatically get the needed plug-ins.
Install Android SDK: This is where you should start if you already have the right versions of Eclipse and the JDK loaded. The Android SDK is distributed through Google’s Android site, http://developer.android.com/sdk/1.1_r1/index.html. You will need to read, review, and accept the terms of the license to proceed. When you get to the list of downloads, you will see a table of distributions. Select the one for your operating system (XP and Vista use the same distribution). The package (file) names include the release number. For example, as this is written, the latest version of the SDK is 1.1_r1, so the filename for Windows is android-sdk-windows-1.1_r1.zip.
For versions 3.3 and later of Eclipse, the Android download site provides directions about how to install the plug-in through Eclipse’s software updates utility. If you’re using Eclipse 3.2 or the software update technique doesn’t work for you, download the SDK from the Android site and install it using instructions in the next paragraph.
The file you download is another archive file, as with Eclipse: a ZIP file on Windows, a tar-zipped file for Linux and MacOS X. Do the same thing as for Eclipse: extract the archive file to a directory where you want to install Android, and make a note of the directory name (you’ll need it in step 6). The extraction will create a directory tree containing a bunch of subdirectories, including one called tools.
Update the environment variables: To make it easier to launch the Android tools, add the tools directory to your path.
On Windows XP, click on Start, then right-click on My Computer. In the pop-up menu, click on Properties. In the resulting System Properties dialog box, select the Advanced tab. Near the bottom of the Advanced tab is a button, “Environment Variables,” that takes you to an Environment Variables dialog. User environment variables are listed in the top half of the box, and System environment variables in the bottom half. Scroll down the list of System environment variables until you find “Path”; select it, and click the “Edit” button. Now you will be in an Edit System Variable dialog that allows you to change the environment variable “Path.” Add the full path of the tools directory to the end of the existing Path variable and click “OK.” You should now see the new version of the variable in the displayed list. Click “OK” and then “OK” again to exit the dialog boxes.
On Windows Vista, click on the Microsoft “flag” in the lower left of the desktop, then right-click on Computer. At the top of the resulting display, just below the menu bar, click on “System Properties.” In the column on the left of the resulting box, click on “Advanced system settings.” Vista will warn you with a dialog box that says “Windows needs your permission to continue”; click “Continue.” Near the bottom of the System Properties box is a button labeled “Environment Variables” that takes you to an Environment Variables dialog. User environment variables are listed in the top half of the box, and System environment variables in the bottom half. Scroll down the list of System environment variables until you find “Path”; select it, and click the “Edit” button. Now you will be in an Edit System Variable dialog that allows you to change the environment variable “Path.” Add the full path of the tools directory to the end of the existing Path variable, and click “OK.” You should now see the new version of the variable in the displayed list. Click “OK” and then “OK” again to exit the dialog boxes.
On Linux, the PATH environment variable can be defined in your ~/.bashrc ~/.bash_profile file. If you have either of those files, use a text editor such as gedit, vi, or Emacs to open the file and look for a line that exports the PATH variable. If you find such a line, edit it to add the full path of the tools directory to the path. If there is no such line, you can add a line like this:
export PATH=${PATH}:your_sdk_dir
/tools
where you put the full path in place of
your_sdk_dir
.
On Mac OS X, look for a file named .bash_profile in your home directory (note the initial dot in the filename). If there is one, use an editor to open the file and look for a line that exports the PATH variable. If you find such a line, edit it to add the full path of the tools directory to the path. If there is no such line, you can add a line like this:
export PATH=${PATH}:your_sdk_dir
/tools
where you put the full path in place of
your_sdk_dir
.
Install the Android plug-in (ADT): Throughout this book, we will make use of the Android Development Tool plug-in that Google supplies for use in building Android applications. The plug-in is installed in much the same way as any other Eclipse plug-in:
Start Eclipse, if it’s not already running.
From the menu bar, select “Help → Software Updates → Find and Install...”.
In the Install/Update dialog, select “Search for new features to install” and click on “Next.”
In the Install dialog, click on “New Remote Site.” A “New Update Site” dialog pops up. Enter a name for the plug-in (“Android Plugin” will do), and the URL for updates: https://dl-ssl.google.com/android/eclipse. Click “OK.”
The new site should now appear in the list of sites on the Install dialog. Click “Finish.”
In the Search Results dialog, select the checkbox for “Android Plugin → Developer Tools” and click “Next.”
The license agreement for the plug-in appears. Read it, and if you agree, select “Accept terms of the license agreement” and click “Next.” Click “Finish.”
You will get a warning that the plug-in is not signed. Choose to install it anyway by clicking “Install All.”
Restart Eclipse.
After Eclipse restarts, you need to tell it where the SDK is located. From the menu bar, select “Window → Preferences.” In the Preferences dialog, select “Android” in the left column.
Use the “Browse” button to navigate to the place you installed the Android SDK, and click on “Apply,” then on “OK.”
Congratulations—you have installed a complete Android development environment without spending a penny. As you’ll see in this and subsequent chapters, the environment includes a very sophisticated set of tools to make Android programming easier, including:
An Integrated Development Environment based on Eclipse, arguably the premier IDE for Java development. Eclipse itself brings many valuable development features. Google and OHA have taken advantage of Eclipse’s extensibility to provide features customized for Android, including debugging capabilities that are tuned to the needs of mobile application developers like you.
A Java development environment and Dalvik virtual machine that build on Sun’s JDK foundation to provide a very sophisticated programming environment for your applications.
A complete mobile phone emulator that allows you to test your applications without having to download them to a target mobile phone. The emulator includes features for testing your application under different mobile phone communication conditions (fading, dropped connections, etc.).
Test tools, such as Traceview, which allow you to tune your application to take best advantage of the limited resources available on a mobile phone.
So enough downloading; let’s write a program. A “Hello World!” program is traditional, and we will start with something similar to demonstrate what you need to do to create, build, and test an Android application. We won’t explore much of the Android API for this program—that’s left for the following chapters—but here we’ll get a taste for the development environment and the steps you go through to create an application for Android.
There isn’t much functionality in this program. We just want to display some text on the Android emulator window that says “Hello Android!” (see Figure 2-1).
Several components are needed to build an Android application. Fortunately, the Eclipse IDE with the Android plug-in automates a lot of the work needed to create and maintain these components. We will start by using the IDE to create a project for our application. Start up Eclipse and select “File → New → Project...” from the menu bar (be sure to select “Project...”, not “Java Project”). You’ll see a list of project types, similar to the menu in Figure 2-2.
Select “Android Project” and click “Next” to get the “New Android Project” dialog box (Figure 2-3).
We’ll use “HelloWorld” as the name for both the Project and
the Application. You don’t need to change the button or checkbox
selections, and we’ll use the package name com.oreilly.helloworld
as shown.
Every Android application has to have at least one Activity
(an executable that usually has a user interface), so let’s say
we’re going to include an Activity called HelloWorldActivity
, as shown in the
dialog box. Click “Finish,” and the Android Software Development Kit
does a number of things for you, to make your life easier as a
developer. In Figure 2-4, I’ve expanded the tree
in the Package Explorer window to show some of the files and
directories that the Android SDK created.
The Android SDK created a HelloWorld directory in the default Eclipse workspace for your project. It also created subdirectories for your source files (.src), references to the Android Library, assets, resources (.res), and a manifest file (AndroidManifest.xml). In each of the subdirectories it created another level of subdirectories as appropriate. Let’s take a quick look at them:
Contains a directory structure that corresponds to the package name you gave for your application: in this case, com.android.helloworld.
Contains a Java template for the Activity you
indicated was in the application (HelloWorldActivity
) and may
contain a directory of resource references (R.java). R.java is actually generated by
the Android SDK the first time you compile your
application; it contains the Java version of all the
resources you define in the res directory (covered later).
We’ll come back to R.java later.
This is just what it says. If you like, you can expand the android.jar tree and see the names of the modules included in the library. This is where your application will go for Android library references.
Files you want to bundle with your application. We won’t have any for HelloWorld.
Drawable resources are any images, bitmaps, etc., that you need for your application. For HelloWorld, the Android SDK has supplied us with the default Android icon, and that’s all we’ll need.
Layout resources tell Android how to arrange items on the screen when the application runs. These resources are XML files that give you quite a bit of freedom in laying out the screen for different purposes. For HelloWorld, we’ll just use the defaults generated by the Android SDK.
Values are constants, strings, etc., available for use by your application. Keeping them outside the sources makes it easier to customize the application, such as adapting it for different languages.
This is another XML file that tells the Android build system what it needs to know to build and package your application so it can be installed on an Android phone or the emulator. This file has its own specialized editor, which we’ll describe when we get to more complicated applications.
In the Eclipse Package Explorer window, double-click on HelloWorldActivity.java
. This opens the
source file of that name in the center window, ready for
editing:
package com.oreilly.helloworld; import android.app.Activity; import android.os.Bundle; public class HelloWorldActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Looking quickly at the template code that the Android SDK has provided for us, we can note several things:
The Android SDK has included the package reference we asked for, which is consistent with the directory structure it created.
It has also created a (collapsed) set of imports for the library references it knows we need.
It created a class definition for the Activity we said we
wanted (HelloWorldActivity
), including a
method called OnCreate
.
For the moment, don’t worry about the parameter passed
into OnCreate
. The savedInstanceState
Bundle is a way of passing data between activities and
storing data between instantiations of the same Activity. We
won’t need to use this for HelloWorld.
One special line of code has been included in OnCreate
:
setContentView (R.layout.main);
Remember that Android uses layouts to define screen layouts on the target, and that main.xml was the name of the default layout file that the Android SDK created for us under .res/layout. The R.java file is generated automatically and contains Java references for each of the resources under .res. You will never need to edit the R.java file by hand; the Android SDK takes care of it as you add, change, or delete resources.
Again in the Eclipse Package Explorer window, double-click on main.xml and you will see the default layout screen in the center window. There are two tabs at the bottom of the panel that say “Layout” and “main.xml”. Click on the one that says “main.xml” to bring up the code version:
<?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="@string/hello" /> </LinearLayout>
Again, let’s look at the key features of this template code:
Like any other XML file, this one starts with a reference to the XML version and encoding used.
LinearLayout is one of the screen layout formats provided by the Android SDK. There are several others, which can be combined hierarchically to create very complex screen layouts. For our purposes, a simple linear layout is fine. More Layout types are covered later in the book in Chapter 11.
The LinearLayout definition:
xmlns:android="http://schemas.android.com/apk/res/android"
identifies the XML schema being used.
This code:
android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
defines an orientation, width, and height for the entire scope of the layout.
TextView describes an area where text can be displayed and edited. It resembles the text boxes you may have encountered when programming in other graphical environments.
Within the TextView definition:
android:layout_width="fill_parent" android:layout_height="wrap_content"
define a width and height for the TextView box.
This code:
android:text="@string/hello"
provides some text to display in the TextView. The actual string is defined in a separate file, res/values/strings.xml. If we open that file (again by clicking on it in the Package Explorer), we see a specialized string editor added by ADT. If you select “hello (String)” by clicking on it, you’ll see the current value for that string. By a stroke of luck, the Android SDK has already included text that is close to what we wanted to display anyway. Just to show them who’s boss, change the value of the String hello to say “Hello Android!”, or something else equally clever.
Save the Project either from the Eclipse File menu (File → Save) or by clicking on the disk icon in the menu bar.
Believe it or not, we’re done. We don’t have to write a single line of Java to create this application.
From the Eclipse menu bar, select Run → Run. A “Run As” dialog box will pop up. Select “Android Application” from the list, which displays the dialog shown in Figure 2-5.
A command window will pop up, followed quickly by an emulator window that looks just like a mobile phone. The emulated phone will then go through its boot sequence, which takes a few minutes (relax; if anything goes wrong, it will tell you). After a few minutes you should see the screen shown in Figure 2-6.
Notice anything different between that screen image and the
one we showed in Figure 2-1? The application
prints out “Hello Android!”, or whatever you wrote into the android:text
line earlier, but it also
displays the title of the application as “Hello World”. Let’s change
the title to match our creative change to the application
text.
In the Package Explorer in the left panel of the Eclipse workbench, reopen the
strings.xml file (the one where
we found the String hello
before). This will open the file in the editing window. The intent
of this file is to give you a place to define strings that will be
used by your application, without actually embedding them in the
Java source code. The other string that’s defined here is app_name
. To make things consistent,
change the definition of app_name
to HelloAndroid
, as shown in
Figure 2-7.
Now when we run the application, we get a screen that looks just like what we set out to do, as shown previously in Figure 2-1.
Congratulations! You’ve just created your first Android program by doing nothing more than changing the text in one line of code. There are much greater challenges ahead.
3.239.76.211