Os Eclipse Android PDF
Os Eclipse Android PDF
26 Feb 2008
Why do we care about Android? Android is an important platform for two reasons.
First, the fact that Google is introducing it and the mind-share Android has garnered
in such a small amount of time. Google is flexing its muscles and attempting to make
a play for the crowded mobile market. Its first salvo into this market, Android and the
Open Handset Alliance, is an impressive starting point. The second reason Android
is important is because it isn't just another mobile platform with a phone, menus, and
a touchscreen. As you will learn in this tutorial, Android takes a different approach to
applications. The architecture of Android permits a highly customizable software
environment thanks to its runtime binding of requested actions and the code to
satisfy those requests. Whether it's market-driven considerations or the technical
aspects of Android, it is a platform worth examination.
System requirements
This tutorial requires several technologies that work together. You need all of them
for this tutorial.
Eclipse Platform
Eclipse is the platform upon which the plug-in runs. Get the latest version of
Eclipse Classic (V3.3.1 was used in this tutorial).
Source code
Source code snippets in this tutorial include:
• AndroidManifest.xml snippet — This file is the application deployment
descriptor for Android applications.
• IntentReceiver — This demonstrates the implementation of an
IntentReceiver, which is the class that processes intents as
advertised by the IntentFilter tag in the AndroidManifest.xml file.
• SaySomething.java — This implements an Android activity, the primary
entry point to the sample application of this tutorial.
Android terminology
Android application development under the Eclipse environment requires knowledge
of the Eclipse environment and the Android platform. An understanding of the terms
below is helpful in Android application development with the Eclipse plug-in.
Android
The flagship product of the Open Handset Alliance. This is an open source
operating environment targeted for mobile devices.
Emulator
A software tool representative of another system — This is often an
environment that runs on a personal computer (IBM®, Mac, Linux®) that
emulates another environment, such as a mobile-computing device.
Linux
An open source operating system kernel at the heart of many computing
The second reason Android is important is because of its application model. Android
applications are not monolithic, menu-laden applications that require a great deal of
clicking and tapping to operate. Sure, there are menus and buttons to be tapped, but
Android has an innovative design element to its architecture known as an intent.
The intent
An intent is a construct that permits an application to issue a request, which is
somewhat like a help-wanted sign. It might look like this:
"Available: Application ready and willing to present contact records in clear, concise
manner," or "Available: Application ready and willing to perform a geographic
search."
The IntentFilter
Applications announce their availability to perform these types of operations via a
construct known as an IntentFilter. The IntentFilter is either registered at
runtime or is enumerated in the AndroidManifest.xml file. The following snippet
comes from an Android application that responds to incoming SMS (text) messages:
After this brief introduction to the intent and IntentFilter, the next section
introduces the four main types of Android applications.
Let's take a moment to examine the four main types of Android applications: activity,
services, receivers, and ContentProvider. We will also take a look at the views to
display the user-interface (UI) elements.
Activity
The activity is the most visible and prominent form of an Android application. An
activity presents the UI to an application, along with the assistance of a class known
as a view. The view class is implemented as various UI elements, such as text
boxes, labels, buttons, and other UIs typical in computing platforms, mobile or
otherwise.
An application may contain one or more activities. They are typically on a one-to-one
relationship with the screens found in an application.
package com.msi.samplereceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentReceiver;
The next section introduces Android views, the UI mechanism for putting things on
the screen of an Android device.
Views
The Android activity employs views to display UI elements. Views follow one of the
following layout designs:
LinearVertical
Each subsequent element follows its predecessor by flowing beneath it in a
single column.
LinearHorizontal
Each subsequent element follows its predecessor by flowing to the right in a
single row.
Relative
Each subsequent element is described in terms of offsets from the prior
element.
Table
A series of rows and columns similar to HTML tables. Each cell can hold one
view element.
Once a particular layout (or combination of layouts) has been selected, individual
views are used to present the UI.
• Button
• ImageButton
• EditText
• TextView (similar to a label)
• CheckBox
• Radio Button
• Gallery and ImageSwitcher for displaying multiple images
• List
• Grid
• DatePicker
• TimePicker
• Spinner (similar to a combo box)
• AutoComplete (EditText with auto text-complete feature)
Views are defined in an XML file. Listing 3 shows an example of a simple
LinearVertical layout.
Note that each element has one or more attributes in the Android name space.
The next section walks through obtaining the Android SDK and configuring it for use
with Eclipse.
Once Eclipse is loaded, click the Workbench - Go to the workbench icon on the
main screen.
There are SDK installation versions available for Windows, Mac OS X (Intel® only),
and Linux (i386). Select the latest version of the SDK for the desired platform. Note
that at the time of this writing, the latest Android SDK version is marked m3-rc37a.
The Android SDK is a compressed folder. Download and extract the contents of this
file to a convenient place on your computer. For purposes of this tutorial, the SDK is
installed to c:\software\google\android_m3-rc37a. Obviously, if you are installing this
on Mac OS X and Linux, you should install the SDK where you usually put your
development tools.
Both Eclipse and the Android SDK are installed. It's time to install the Eclipse plug-in
to take advantage of the Eclipse environment.
1. Run the "Find and Install" feature in Eclipse, found under the Help >
Software Updates menu.
3. Select New Remote Site. Give this site a name, such as "Android
Developer Tools," for example. Use the following URL in the dialog:
https://dl-ssl.google.com/android/eclipse. Please note the HTTPS in the
URL. This is a secure download.
Figure 1. New Update Site
4. A new entry is added to the list and is checked by default. Click Finish.
The search results display the Android Developer Tools. Select the
Developer Tools and click Next.
5. After reviewing and accepting the license agreement, click Next. Note
that the license agreement includes a special requirement for use of the
Google Maps API.
The plug-in is now downloaded and installed. The plug-in is not signed (at the time
of writing), so proceed at your own comfort level by clicking on Install All, then
restart Eclipse.
Once the SDK location is specified, there are three other sections that may be
configured. They are mentioned here briefly:
• Name
• Location
• Package name
• Activity name — Think of this as the main "form" or screen of the
application
• Application name
Take a look at the new project.
This will create a default application ready to be built and run. The components may
be seen in the Package Explorer, which we discuss next.
src folder
Includes the package for the sample application, namely
com.msi.ibmtutorial
R.java
The Android Developer Tools create this file automatically and represents the
constants needed to access various resources of the Android application. More
on the relationship between the R class and resources is found below.
SaySomething.java
Implementation of the application's primary activity class.
Referenced libraries
Contains android.jar, which is the Android runtime class jar file, found in the
Android SDK.
res folder
Contains the resources for the application, including:
• Icons
• Layout files
• Strings
AndriodManifest.xml
Deployment descriptor of the sample application.
Listing 4. SaySomething.java
package com.msi.ibmtutorial;
import android.app.Activity;
import android.os.Bundle;
public class SaySomething extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
}
}
Drawables
This folder contains graphics files, such as icons and bitmaps
Layouts
This folder contains XML files that represent the layouts and views of the
application. These will be examined in detail below.
Values
This folder contains a file named strings.xml. This is the primary means for
string localization for the application.
The next section dissects the main.xml file to review the sample application's
primary UI resources.
main.xml
The sample application contains a single activity and a single view. The application
contains a file named main.xml that represents the visual aspects of the primary UI
of the activity. Note that there is no reference in the main.xml where the layout is
used. This means it may be used in more than one activity, if desired. Listing 5
contains the content of the layout file.
This is the most simplistic of layouts. There is a single linear layout, which is oriented
as a vertical layout, meaning all contained elements are in a single column. There is
a single TextView element, which can be likened to a label in other development
environments. A TextView represents static text that is not editable.
Note that each view element (layout and TextView in this example) have
attributes in the Android name space. Some attributes are common to all views —
the android:layout_width and android:layout_height attributes, for
example. The values available for these attributes are:
Fill Parent
This extends the view element to take the maximum space available. This can
also be thought of as meaning "stretch."
Wrap Content
This value tells Android to paint the elements one after the next without
stretching.
During the build process, all resources are compiled. One of the products of that
process is the R.java file, which represents the resources to the remainder of the
application. The R.java file is discussed next.
R.java
The R.java file is created upon build automatically, so be sure to not modify it by
hand as all changes will be lost. Listing 6 contains the R.java file for the sample
application.
The R class contains anonymous subclasses, which each contain identifiers for the
various resources previously described. Note that all of these classes are static.
Note the element represented by: R.layout.main. This identifier represents the layout
defined by main.xml. Recall that this value is used in the onCreate method of the
activity as follows: setContentView(R.layout.main);. This is the point at
which a specific activity (in this case, SayAnything) and a specific layout (main)
are bound together at runtime.
Building applications
Files are compiled every time they are saved by default.
We introduced an error into the source code where we added an extra space
between setContent and View. When the file is saved, it is compiled and any
errors appear in the Problems pane at the bottom of the screen. Upon fixing the
error in the source code, the application builds properly and the errors are removed
from the problems list.
AndroidManifest.xml
The AndroidManifest.xml file represents the deployment descriptor for an Android
application. The file lists any activity, service, content provider, or receiver contained
in the application, along with the appropriate IntentFilters supported by the
application. Here is the complete AndroidManifest.xml file for the sample application:
</manifest>
Things to note:
• The package name from the source file is represented here. This follows
a similar pattern to a Java source file and imports. The <manifest> tag
is in essence "importing" classes from this package. All non-fully qualified
classes in this file are found in the package identified in the package
attribute.
• The <application> tag has an attribute that references a resource
from the application's resources. Note the @ symbol preceding the
drawable identifier. This is a hint for the file to look in the drawable folder
of the application's resources for a resource called "icon."
• The <activity> tag contains the following attributes and values of note:
• class represents the Java class implementing this activity
• android:label is the name of the application. Note that it is coming
from one of the string resources. The string.xml file contains localized
strings for the application.
• <intent-filter> represents the IntentFilter available in the
sample application. This is the most common IntentFilter seen in
Android applications. This filter essentially says that it implements the
"main" action (or entry point) and is located in the launcher of the OS.
In English, this means it can be started as an application from the
primary list of applications on an Android device.
The next section describes starting the application on the Android Emulator from
within Eclipse.
Give the configuration a name. The tutorial sample uses the name Tutorial
Configuration. Select the ibmtutorial project from the list of available projects (click
Browse to see available projects). Select the startup activity in the drop-down. Now
select the Emulator tab to specify Emulator settings, as desired. The default can be
left alone. There are a couple of items to note, as described in Figure 7.
There are a few screen sizes and orientations to choose from, as well as network
choices. The network choices are important when building applications that employ
Internet connectivity as mobile devices have varying network speed capabilities.
Choose full network speed and no latency when prototyping an application. Once
the main functionality is present, it's a good idea to test with less-than-ideal network
conditions to see how the application responds in situations with suboptimal network
connectivity.
Figure 8. Emulator
Now that the application is running on the Emulator, it's time to see what's
happening behind the scenes. The Dalvik Debug Monitor Service (DDMS) will assist
with this.
The LogCat is a running log file of activity taking place in the VM. Applications can
make their own entries to this list with a simple line of code as follows:
Log.i(tag,message);, where tag and message are both Java strings. The Log
class is part of the android.util.Log package.
Another handy tool in the DDMS is the file explorer, which permits file system
access of the Emulator. Figure 10 shows where the tutorial's sample application is
deployed on the Emulator.
User applications are deployed in /data/app while Android built-in applications are
found in the /system/app directory.
contacts recorded and be sure to populate the home address field. Figure 12 shows
the Emulator with a few entries in the contact application.
Here is the first of two code snippets for the second application. Note that this
application's main Activity class extends the ListActivity. This is because
we're going to display information in a list.
Note the use of the cursor class to query the contacts database. This "result set"
cursor is linked to the UI via a class known as a ListAdapter. Figure 13 shows the
application in action as it presents the contacts available on the device. Note that
there is no sort order in use in this display.
Any one of the contacts may be selected by a tap (click of the mouse), the center
button on the emulator, or by pressing the Enter key on your keyboard. Once this
entry is selected, the code must perform a lookup to obtain the address of the
selected contact. This is where the onListItemClick() overridden method
comes into play. This method's implementation has four important arguments. The
one of most interest here is the dbidentifier method. Because the cursor was
bound to the UI, when this method is invoked, it actually receives an identifier to the
underlying data source. The dbidentifier field may be used to query the
contacts database for desired information. It can also be used to simply launch the
contacts application using an intent as shown in the commented-out code in Listing
7.
@Override
protected void onListItemClick(ListView list,View view,int position,long
dbidentifier)
{
super.onListItemClick(list,view,position,dbidentifier);
try
{
// this commented out code below will launch the Contacts application
// and "view" the contact Intent myIntent = \
new Intent(android.content.
// Intent.VIEW_ACTION,new ContentURI("content://contacts/people/"
// + dbidentifier)); startSubActivity(myIntent,position);
// IMPORTANT
// in order to use this sample application, you need to have at least
// one Contact record on your Android emulator\
// and be sure to have populated the 'Home Address field'
//
// this "where clause" is for HOME address and for the person record
// selected in the GUI (id, dbidentifier)
Cursor c = managedQuery(theContact,null," type = 1 and person = " +
dbidentifier,null);
if (!c.first())
{
showAlert("MSCC","No Contact Methods Available!","",true);
return;
}
Once the address has been obtained, a few simple string operations are required to
clean up the data to prepare it for a query to Google Maps. The geoIntent is a
new Intent created to perform a geo search, which in the default Android Emulator
image is satisfied by a call to Google Maps.
All of the major elements of the first application still hold true for this application.
There is a single activity launched from the main application screen. There is, of
course, the AndroidManifest.xml file identifying our new application. Remember,
complete source code is available in the Download section.
There is one final piece of information that is important to this second example
application. In the AndroidManifest.xml file, there is an additional entry that gives the
application permission to read the contacts database: <uses-permission
id="android.permission.READ_CONTACTS" />. Without this explicit
permission, the Linux kernel will prevent the application from accessing the contacts
database.
Section 7. Summary
This tutorial introduced the Android platform, the Android Developer Tools, and the
key elements of Android development in Eclipse. The Android Developer Tools
allows you to leverage the rich Eclipse development environment for building and
testing Android applications. You should now be ready to create your own Android
applications.
Downloads
Description Name Size Download method
Example source code os-eclipse-android.examples.zip
67KB HTTP
Resources
Learn
• The author's Android book is available in part online at Manning Publications.
• The authoritative Android information source is Google's Android Web site,
where you can find project documentation and links to download the Android
SDK.
• Check out the "Recommended Eclipse reading list."
• Read the tutorial "Build a mobile RSS reader" to learn how to read, parse, and
display RSS or other XML data in mobile apps, including your own mash-ups,
using the Android Developer Tools.
• Browse all the Eclipse content on developerWorks.
• New to Eclipse? Read the developerWorks article "Get started with Eclipse
Platform" to learn its origin and architecture, and how to extend Eclipse with
plug-ins.
• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project
resources.
• To listen to interesting interviews and discussions for software developers,
check out check out developerWorks podcasts.
• Stay current with developerWorks' Technical events and webcasts.
• Watch and learn about IBM and open source technologies and product
functions with the no-cost developerWorks On demand demos.
• Check out upcoming conferences, trade shows, webcasts, and other Events
around the world that are of interest to IBM open source developers.
• Visit the developerWorks Open source zone for extensive how-to information,
tools, and project updates to help you develop with open source technologies
and use them with IBM's products.
Get products and technologies
• Check out the latest Eclipse technology downloads at IBM alphaWorks.
• Install the Eclipse Android Development Tools (ADT) plug-in using Eclipse
software update. You can also download the Android SDK and learn how to
install, configure, and use the Android SDK.
• Download Eclipse Platform and other projects from the Eclipse Foundation.
• Download IBM product evaluation versions, and get your hands on application
development tools and middleware products from DB2®, Lotus®, Rational®,