Developing an End User Application with the Android SDK


Build your own Android App Dev Empire

Get Instant Access

In this section, we'll introduce you to the high-level Android Java APIs that you'll use to develop end-user applications for an Android handheld. We will briefly talk about the Android phone emulator and foundational components, UI programming, services, media, telephony, animation, and OpenGL. We will also show you some code snippets when they are helpful.

The Android Emulator

The Android SDK ships with an Eclipse plug-in called Android Development Tools (ADT). You will use this Integrated Development Environment (IDE) tool for developing, debugging, and testing your Java applications. (We'll cover ADT in depth in Chapter 2.)

You can also use the Android SDK without using ADT; you'd use command-line tools instead. Both approaches support an emulator that you can use to run, debug, and test your applications. You will not even need the real device for 90 percent of your application development.

The full-featured Android emulator mimics most of the device features, but you'll encounter some limitations regarding USB connections, camera and video capture, headphones, battery simulation, and Bluetooth.

The Android emulator accomplishes its work through an open source "processor emulator" technology called QEMU ( developed by Fabrice Bellard. This is the same technology that allows emulation of one operating system on top of another, irrespective of the processor. QEMU allows emulation at the CPU level.

In the case of the Android emulator, the processor is based on ARM (Advanced RISC Machine). ARM is a 32-bit microprocessor architecture based on RISC (Reduced Instruction Set Computer), in which design simplicity and speed is achieved through a reduced number of instructions in an instruction set. The emulator actually runs the Android version of Linux on this simulated processor. PowerPCs supporting Apple Macs and SPARC chips supporting Sun workstations are examples of RISC architectures.

ARM is widely used in handhelds and other embedded electronics where lower power consumption is important. Much of the mobile market uses processors based on this architecture. For example, Apple Newton is based on the ARM6 processor. Devices such as the iPod, Nintendo DS, and Game Boy Advance run on ARM architecture version 4 with approximately 30,000 transistors. Compared to that, the Pentium classic contains 3,200,000 (3.2 million) transistors.

You can find more details about the emulator in the Android SDK documentation at

The Android UI

Android uses a UI framework that resembles other desktop-based, full-featured UI frameworks, but it's more modern and more asynchronous in nature. Android is almost a fourth-generation UI framework if you were to call the traditional C-based Microsoft Windows API the first generation and the C++-based MFC (Microsoft Foundation Classes) the second generation. The Java-based Swing UI framework would be the third generation, introducing design flexibility far beyond that offered by MFC. The Android UI, JavaFX, Microsoft Silverlight, and Mozilla XML User Interface Language (XUL) fall under this new type of fourth-generation UI framework in which the UI is declarative and independently themed.

■Note The noteworthy aspect of UI programming in Android is that you are programming in a modern UI paradigm even though the device happens to be a handheld.

Programming in the Android UI involves declaring the interface in XML files. You will then load these XML view definitions as windows in your UI application. Even menus in your application are loaded from XML files. Screens or windows in Android are often referred to as activities, which comprise multiple views that a user needs in order to accomplish a logical unit of action. Views are Android's basic UI building blocks, and you can further combine them to form composite views called view groups. Views internally use the familiar concepts of canvases, painting, and user interaction. An activity hosting these composite views, which include views and view groups, is the logical replaceable UI component in Android.

One of the Android framework's key concepts is the lifecycle management of activity windows. Protocols are put in place so that Android can manage state as users hide, restore, stop, and close activity windows. You will get a feel for these basic ideas in Chapter 2, along with an introduction to setting up the Android development environment.

The Android Foundational Components

The Android UI framework, along with other parts of Android, relies on a new concept called an intent. An intent is an amalgamation of ideas such as windowing messages, actions, publish-and-subscribe models, interprocess communications, and application registries. Here is an example of using the Intent class to invoke or start a web browser:

public static void invokeWebBrowser(Activity activity) {

Intent intent = new Intent(Intent.ACTION_VIEW);



Through an intent, we are asking Android to start a suitable window to display the content of a web site. Depending on the list of browsers that are installed on the device, Android will choose a suitable one to display the site. You will learn more about intents in Chapter 3.

Android also has extensive support for resources, which include familiar elements and files such as strings and bitmaps, as well as some not-so-familiar items such as XML-based view definitions. The framework makes use of resources in a novel way to make their usage easy, intuitive, and convenient. Here is an example where IDs are automatically generated for resources defined in XML files:

public final class R {

public static final class attr { } public static final class drawable {

public static final int myanimation=0x7f020001; public static final int numbers19=0x7f02000e;

public static final class id {

public static final int textViewId1=0x7f080003;

public static final class layout {

public static final int frame_animations_layout=0x7f030001; public static final int main=0x7f030002;

public static final class string {

public static final int hello=0x7f070000;

Each auto-generated ID in this class corresponds to either an element in an XML file or a whole file itself. Wherever you would like to use those XML definitions, you can use these generated IDs instead. This indirection helps a great deal when it comes to localization. (Chapter 3 covers the file and resources in more detail.)

Another new concept in Android is the content provider. A content provider is an abstraction on a data source that makes it look like an emitter and consumer of RESTful services. The underlying SQLite database makes this facility of content providers a powerful tool for application developers. (In Chapter 3, we'll discuss how intents, resources, and content providers promote openness in the Android Platform.)

Advanced UI Concepts

We have pointed out that XML plays a role in describing the Android UI. Look at an example of how XML does this for a simple layout containing a text view:

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

<LinearLayout xmlns:android=> <TextView android:id="@+id/textViewId"

android:layout_width="fill_parent" android:layout_height="wrap_content"



You will then use an ID generated for this XML file to load this layout into an activity window. (We'll cover these ideas further in Chapter 4.)

Android also provides extensive support for menus, from standard menus to context menus. You'll find it convenient to work with menus in Android because they are also loaded as XML files and because resource IDs for those menus are auto-generated. Here's how you would declare menus in an XML file:

<menu xmlns:android=""> <!-- This group uses the default category. --> <group android:id="@+id/menuGroup_Main"> <item android:id="@+id/menu_clear" android:orderInCategory="10" android:title="clear" /> <item android:id="@+id/menu_show_browser" android:orderInCategory="5" android:title="show browser" />

Although Android supports dialogs, all dialogs in Android are asynchronous. These asynchronous dialogs present a special challenge to developers accustomed to the synchronous modal dialogs in some windowing frameworks. We'll address menus and dialogs more extensively in Chapter 5, where we'll also provide a number of mechanisms to deal with asynchronous-dialog protocols.

Android also offers support for animation as part of its UI stack based on views and drawable objects. Android supports two kinds of animation: tweening animation and frame-by-frame animation.

"Tweening" is a term in animation that refers to the drawings that are "in between" the key drawings. You accomplish this with computers by changing the intermediate values at regular intervals and redrawing the surface. Frame-by-frame animation occurs when a series of frames is drawn one after the other at regular intervals. Android enables both animation approaches through animation callbacks, interpolators, and transformation matrices. Moreover, Android allows you to define these animations in an XML resource file. Check out this example, in which a series of numbered images is played in frame-by-frame animation:

<animation-list xmlns:android="" android:oneshot="false"> <item android:drawable="@drawable/numbers11" android:duration="50" />

<item android:drawable="@drawable/numbers19" android:duration="50" /> </animation-list>

The underlying graphics libraries support the standard transformation matrices, allowing scaling, movement, and rotation. A Camera object in the graphics library provides support for depth and projection, which allows 3D-like simulation on a 2D surface. (We'll explore animation further in Chapter 6.)

Android also supports 3D graphics through its implementation of the OpenGL ES 1.0 standard. OpenGL ES, like OpenGL, is a C-based flat API. The Android SDK, because it's a Java-based programming API, needs to use Java binding to access the OpenGL ES. Java ME has already defined this binding through Java Specification Request (JSR) 239 for OpenGL ES, and Android uses the same Java binding for OpenGL ES in its implementation. If you are not familiar with OpenGL programming, the learning curve is steep. But we've reviewed the basics here, so you'll be ready to start programming in OpenGL for Android in Chapter 10.

Starting with release 1.5 Android has simplified OpenGL so that it is approachable to beginning OpenGL programmers. We will cover these improvements in Chapter 13. Additionally, that SDK introduced a new concept called live folders, which we will also cover in Chapter 13.

Android Service Components

Security is a fundamental part of the Android Platform. In Android, security spans all phases of the application lifecycle—from design-time policy considerations to runtime boundary checks. Location-based service is another one of the more exciting pieces of the Android SDK. This portion of the SDK provides application developers APIs to display and manipulate maps, as well as obtain real-time device-location information. We'll cover these ideas in detail in Chapter 7.

In Chapter 8, we'll show you how to build and consume services in Android, specifically HTTP services. The chapter will also cover interprocess communication (communication between applications on the same device). Here is an example of doing an HttpPost in Android:

InputStream is = this.getAssets().open("data.xml"); HttpClient httpClient = new DefaultHttpClient();

HttpPost postRequest = new HttpPost("");

byte[] data = IOUtils.toByteArray(is);

InputStreamBody isb = new InputStreamBody(

new ByteArrayInputStream(data),"uploadedFile"); StringBody sb1 = new StringBody("someTextGoesHere"); StringBody sb2 = new StringBody("someTextGoesHere too");

MultipartEntity multipartContent = new MultipartEntity(); multipartContent.addPart("uploadedFile", isb); multipartContent.addPart("one", sb1); multipartContent.addPart("two", sb2);

postRequest.setEntity(multipartContent); HttpResponse res =httpClient.execute(postRequest); res.getEntity().getContent().close();

Android Media and Telephony Components

Android has APIs that cover audio, video, and telephony components. Here is a quick example of how to play an audio file from an Internet URL:

private void playAudio(String url)throws Exception {

mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(internetUrl); mediaPlayer.prepare(); mediaPlayer.start();

And here's an example of playing an audio file from the local device:

private void playLocalAudio()throws Exception {

//The file is located in the /res/raw directory and called "music_file.mp3" mediaPlayer = MediaPlayer.create(this, R.raw.music_file); mediaPlayer.start();

We'll cover these audio and video APIs extensively in Chapter 9. The chapter will also address the following aspects of the telephony API:

• Sending and receiving Short Message Service (SMS) messages

• Monitoring SMS messages

• Managing SMS folders

• Placing and receiving phone calls

Here is an example taken from that chapter on sending an SMS message:

private void sendSmsMessage(String address,String message)throws Exception {

SmsManager smsMgr = SmsManager.getDefault(); smsMgr.sendTextMessage(address, null, message, null, null);

Prior to the 1.5 release you could record audio but not video. Both audio and video recording are accommodated in 1.5 through MediaRecorder. This is covered with examples in Chapter 12. Chapter 12 also covers voice recognition, along with the input-method framework (IMF), which allows a variety of inputs to be interpreted as text while typing into text controls. The input methods include keyboard, voice, pen device, mouse, etc. This framework was originally designed as part of Java API 1.4; you can read more about it at the following Java site:

Last but not least, Android ties all these concepts into an application by creating a single XML file that defines what an application package is. This file is called the application's manifest file (AndroidManifest.xml). Here is an example:

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

<manifest xmlns:android="" package="" android:versionCode="1" android:versionName="1.0.0"> <application android:icon="@drawable/icon" android:label="@string/appjiame"> <activity android:name=".HelloWorld"

android:label="@string/appjiame"> <intent-filter>

<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

The Android manifest file is where activities are defined, where services and content providers are registered, and where permissions are declared. Details about the manifest file will emerge throughout the book as we develop each idea.

Android Java Packages

One way to get a quick snapshot of the Android Platform is to look at the structure of Java packages. Because Android deviates from the standard JDK distribution, it is important to know at a high level what is supported and what is not. Here's a brief description of the important Java packages that are included in the Android SDK:

• Implements the Application model for Android. Primary classes include Application, representing the start and stop semantics, as well as a number of activity-related classes, controls, dialogs, alerts, and notifications.

• android.appwidget: Implements the mechanism for allowing applications to publish their views in other applications, such as the home page. The primary classes include AppWidgetHost, AppWidgetHostView, AppWidgetManager, AppWidgetProvider, and AppWidgetProviderInfo. This package is available only in SDK 1.5.

• android.content: Implements the concepts of content providers. Content providers abstract out data access from data stores. This package also implements the central ideas around intents and Android Uniform Resource Identifiers (URIs).

• Implements Package Manager-related classes. A package manager knows about permissions, installed packages, installed providers, installed services, installed components such as activities, and installed applications.

• android.content.res: Provides access to resource files both structured and unstructured. The primary classes are AssetManager (for unstructured resources) and Resources.

• android.database: Implements the idea of an abstract database. The primary interface is the Cursor interface.

• android.database.sqlite. Implements the concepts from the android.database package using SQLite as the physical database. Primary classes are SOLiteCursor, SOLiteDatabase, SOLiteOuery, SOLiteOueryBuilder, and SOLiteStatement. However, most of your interaction is going to be with classes from the abstract android.database package.

• Contains the classes Bitmap, Canvas, Camera, Color, Matrix, Movie, Paint, Path, Rasterizer, Shader, SweepGradient, and TypeFace.

• Implements drawing protocols and background images, and allows animation of drawable objects.

• Implements shapes including ArcShape, OvalShape, PathShape, RectShape, and RoundRectShape.

• android.hardware. Implements the physical Camera-related classes. This Camera represents the hardware camera, whereas represents a graphical concept that's not related to a physical camera at all.

• android.inputmethodservice. Implements the interfaces and base abstract classes necessary for writing input methods.

• android.location: Contains the classes Address, GeoCoder, Location, LocationManager, and LocationProvider. The Address class represents the simplified XAL (Extensible Address Language). GeoCoder allows you to get a latitude/longitude coordinate given an address, and vice versa. Location represents the latitude/longitude.

• Contains the classes MediaPlayer, MediaRecorder, Ringtone, AudioManager, and FaceDetector. MediaPlayer, which supports streaming, is used to play audio and video. MediaRecorder is used to record audio and video. The Ringtone class is used to play short sound snippets that could serve as ringtones and notifications. AudioManager is responsible for volume controls. You can use FaceDetector to detect people's faces in a bitmap.

• Implements the basic socket-level network APIs. Primary classes include Uri, ConnectivityManager, LocalSocket, and LocalServerSocket.

• Manages WiFi connectivity. Primary classes include WifiManager and WifiConfiguration. WifiManager is responsible for listing the configured networks and the currently active WiFi network.

• android.opengl: Contains utility classes surrounding OpenGL ES operations. The primary classes of OpenGL ES are implemented in a different set of packages borrowed from JSR 239. These packages are javax.microedition.khronos.opengles, javax. microedition.khronos.egl, and javax.microedition.khronos.nio. These packages are thin wrappers around the Khronos implementation of OpenGL ES in C and C++.

• android.os: Represents the OS services accessible through the Java programming language. Some important classes include BatteryManager, Binder, FileObserver, Handler, Looper, and PowerManager. Binder is a class that allows interprocess communication. FileObserver keeps tabs on changes to files. You use Handler classes to run tasks on the message thread, and Looper to run a message thread.

• android.preference. Allows applications the ability to have users manage their preferences for that application in a uniform way. The primary classes are PreferenceActivity, PreferenceScreen, and various Preference-derived classes such as CheckBoxPreference and SharedPreferences.

• android.provider. Comprises a set of prebuilt content providers adhering to the android.content.ContentProvider interface. The content providers include Contacts, MediaStore, Browser, and Settings. This set of interfaces and classes stores the metadata for the underlying data structures.

• android.sax. Contains an efficient set of Simple API for XML (SAX) parsing utility classes. Primary classes include Element, RootElement, and a number of ElementListener interfaces.

• android.speech: Contains constants for use with speech recognition. This package is available only in releases 1.5 and later.

• android.telephony. Contains the classes CellLocation, PhoneNumberUtils, and TelephonyManager. A TelephonyManager lets you determine cell location, phone number, network-operator name, network type, phone type, and Subscriber Identity Module (SIM) serial number.

• android.telephony.gsm: Allows you to gather cell location based on cell towers and also hosts classes responsible for SMS messaging. This package is called GSM because Global System for Mobile Communication is the technology that originally defined the SMS data-messaging standard.

• android.text: Contains text-processing classes.

• android.text.method: Provides classes for entering text input for a variety of controls.

• Provides a number of styling mechanisms for a span of text.

• android.utils: Contains the classes Log, DebugUtils, TimeUtils, and Xml.

• android.view: Contains the classes Menu, View, ViewGroup, and a series of listeners and callbacks.

• android.view.animation: Provides support for tweening animation. The main classes include Animation, a series of interpolators for animation, and a set of specific animator classes that include AlphaAnimation, ScaleAnimation, TranslationAnimation, and RotationAnimation.

• android.view.inputmethod: Implements the input-method framework architecture. This package is available only in releases 1.5 and later.

• android.webkit: Contains classes representing the web browser. The primary classes include WebView, CacheManager, and CookieManager.

• android.widget: Contains all of the UI controls usually derived from the View class. Primary widgets include Button, Checkbox, Chronometer, AnalogClock, DatePicker, DigitalClock, EditText, ListView, FrameLayout, GridView, ImageButton, MediaController, ProgressBar, RadioButton, RadioGroup, RatingButton, Scroller, ScrollView, Spinner, TabWidget, TextView, TimePicker, VideoView, and ZoomButton.

• Contains the classes MapView, MapController, and MapActivity, essentially classes required to work with Google maps.

These are some of the critical Android-specific packages. From this list you can see the depth of the Android core platform.

Note In all, the Android Java API contains more than 36 packages and more than 700 classes.

In addition, Android provides a number of packages in the java.* namespace. These include awt.font, io, lang, lang.annotation, lang.ref, lang.reflect, math, net, nio, nio.channels, nio.channels.spi, nio.charset, security, security.acl, security.cert, security.interfaces, security.spec, sql, text, util, util.concurrent, util.concurrent. atomic, util.concurrent.locks, util.jar, util.logging, util.prefs, util.regex, and

Android comes with these packages from the javax namespace: crypto, crypto.spec, microedition.khronos.egl, microedition.khronos.opengles, net, net.ssl, security.auth, security.auth.callback, security.auth.login, security.auth.x500, security.cert, sql, xml, and xmlparsers.

In addition, it contains a lot of packages from org.apache.http.*. It also carries org.json, org.w3c.dom, org.xml.sax, org.xml.sax.ext, org.xml.sax.helpers, org.xmlpull.v1, and org. xmlpull.v1.sax2.

Together, these numerous packages provide a rich computing platform to write applications for handheld devices.

Was this article helpful?

0 0

Post a comment