- In an internet driven environment, it is imperative for a company to keep its product or business to the forefront of potential customers' minds. The ...
- A successful enterprise is all about constantly reinventing ways to work more efficiently. In today’s techno age, this translates to testing new too...
- The IT industry plays a pivotal role in providing application development solutions and custom software development to a wide range of industries, i...
- Royal Victorian Eye and Ear Hospital, 2010 Atcomm has been contracted to implement a complex IOP glaucoma management tool which will be distribut...
- We are pleased to announce another implementation of a CMS system for a large Melbourne based fitness center - Star Plate Studio. Atcomm has depl...
Learning the Fundamental Components
View
The concept of a view in J2EE and Swing carries over to Android. Views are UI elements that form the basic building blocks of a user interface. Views are hierarchical and they know how to draw themselves.
Activity
An activity is a user interface concept. An activity usually represents a single screen in your application. It generally contains one or more views, but it doesn’t have to. Moreover, other concepts in Android could better represent a viewless activity (as you’ll see in the “Service” section shortly).
Intent
An intent generically defines an “intention” to do some work. Intents encapsulate several concepts, so the best approach to understanding them is to see examples of their use. You can use intents to perform the following tasks, for instance:
• Broadcast a message
• Start a service
• Launch an activity
• Display a web page or a list of contacts
• Dial a phone number or answer a phone call
Intents are not always initiated by your application—they’re also used by the system to notify your application of specific events (such as the arrival of a text message).
Intents can be explicit or implicit. If you simply say that you want to display a URL, the system will decide what component will fulfill the intention. You can also provide specific information about what should handle the intention. Intents loosely couple the action and action handler.
Content Provider
Data sharing among mobile applications on a device is common. Therefore, Android defines a
standard mechanism for applications to share data (such as a list of contacts) without exposing the underlying storage, structure, and implementation. Through content providers, you can expose your data and have your applications use data from other applications.
Service
Services in Android resemble services you see in Windows or other platforms—they’re background processes that can potentially run for a long time. Android defines two types of services: local services and remote services. Local services are components that are only accessible by the application that is hosting the service. Conversely, remote services are services that are meant to be accessed remotely by other applications running on the device.
An example of a service is a component that is used by an e-mail application to poll for new messages. This kind of service might be a local service if the service is not used by other applications running on the device. If several applications use the service, then the service would be implemented as a remote service. The difference, as you’ll see in Chapter 8, is in startService() vs. bindService().
You can use existing services and also write your own services by extending the Service class.
AndroidManifest.xml
AndroidManifest.xml, which is similar to the web.xml file in the J2EE world, defines the contents and behavior of your application. For example, it lists your app’s activities and services,along with the permissions the application needs to run.
Hello World!
Now you’re ready to build your first Android application. You’ll start by building a simple “Hello World!” program. Create the skeleton of the application by following these steps:
1. Launch Eclipse and select File ? New ? Project. In the “New Project” dialog box, select “Android” and then click “Next.” You will then see the “New Android Project” dialog box, as shown in Figure 2-4.
2. As shown in Figure 2-4, enter HelloAndroid as the project name, pro.android as the package name, HelloActivity as the activity name, and HelloAndroidApp as the application name. Note that for a real application, you’ll want to use a meaningful application name because it will appear in the application’s title bar. Also note that the default location for the project will be derived from the Eclipse workspace location. In this case, your Eclipse workspace is c:\Android, and the New Project Wizard appends the name of the new application to the workspace location to come up with
c:\Android\HelloAndroid\.
3. Click the “Finish” button, which tells ADT to generate the project skeleton for you. For now, open the HelloActivity.java file under the src folder and modify the onCreate() method as follows:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** create a TextView and write Hello World! */
TextView tv = new TextView(this);
tv.setText("Hello World!");
/** set the content view to the TextView */
setContentView(tv);
}
Add an import statement for android.widget.TextView. To run the application, you’ll need to create an Eclipse launch configuration (see Figure 2-5).
Create the Eclipse launch configuration by following these steps:
1. Select Run ? Run Configurations.
2. In the “Run Configurations” dialog box, double-click “Android Application” in the left
pane. The wizard will insert a new configuration named “New Configuration.”
3. Rename the configuration RunHelloWorld.
4. Click the “Browse…” button and select the HelloAndroid project.
5. Under “Launch Action,” select “Launch” and select “pro.android.HelloActivity” from the drop-down list.
6. Click “Apply” and then “Run.” You should see the emulator launched with the HelloAndroid project (see Figure 2-6).
Now you know how to create a new Android application and run it in the emulator. Next, we’ll discuss the pieces that make the simple program display in the emulator. We’ll begin by talking about an Android application’s artifacts and structure.
Getting Your Feet Wet
To build applications for Android, you’ll need the Java SE Development Kit (JDK), the Android SDK, and a evelopment environment. Strictly speaking, you can develop your applications using a primitive text editor, but for the purposes of this book, we’ll use the commonly available Eclipse IDE. The examples in this book target Android SDKs 1.1 and 1.5. (Chapters 12 and 13 focus on material specific to Android 1.5.) The Android SDK requires JDK 5 or higher,and we use JDK 6 with the examples. Moreover, the Android SDK requires Eclipse 3.3 or higher; we use Eclipse 3.4 (Ganymede).
Finally, to make your life easier, you’ll want to use Android Development Tools (ADT). ADT is an Eclipse plug-in that supports building Android applications with the Eclipse IDE. In fact, we built all the examples in this book using the Eclipse IDE (version 3.4) with the ADT tool.
Finally, to make your life easier, you’ll want to use Android Development Tools (ADT). ADT is an Eclipse plug-in that supports building Android applications with the Eclipse IDE. In fact, we built all the examples in this book using the Eclipse IDE (version 3.4) with the ADT tool.
Setting Up Your Environment
To build Android applications, you need to establish a development environment. In this section, we are going to walk you through downloading JDK 6, the Eclipse IDE, the Android SDK, and ADT. We’ll also help you configure Eclipse to build Android applications.
Downloading JDK 6 and Eclipse 3.4
The first thing you’ll need is the JDK. As we said earlier, the Android SDK 1.0 requires JDK 5 or higher, and we developed the examples using JDK 6. To get started, download JDK 6 from the Sun web site: http://java.sun.com/javase/downloads/index.jsp.
After you download the JDK, you’ll want to install it and set the JAVA_HOME environment variable to point to the JDK install folder. On a Windows machine, you can do this from a command line by typing this code:
set JAVA_HOME=[YOUR JDK_PATH_GOES_HERE]
Now, you can download the Eclipse IDE for Java Developers (not the edition for Java EE). Again, the examples in this book use Eclipse 3.4 (on a Windows environment), which you can download from http://www.eclipse.org/downloads/.
Downloading the Android SDK
To build applications for Android, you need the Android SDK. The SDK includes an emulator so you don’t need a mobile device with the Android OS to develop Android applications. In fact, we developed the examples in this book on a Windows XP machine.
You can download the Android SDK from http://code.google.com/android/download. html. The Android SDK ships as a .zip file for Windows, so you need to unzip it. Unzip the file to c:\AndroidSDK\, after which you should see the files shown in Figure 2-1.
Installing Android Development Tools (ADT)
Now you need to install ADT, an Eclipse plug-in that helps you build Android applications. Specifically, ADT integrates with Eclipse to provide facilities for you to create, test, and debug Android applications. You’ll need to use the Software Updates facility within Eclipse to perform the installation. If you are using Android 1.1, follow the instructions below. If you are using Android 1.5, refer to Chapter 12 for ADT installation. To get started, launch the Eclipse IDE and follow these instructions:
1. Select the Help menu item and choose the “Software Updates…” option.
2. In the “Software Updates and Add-ons” dialog, select the “Available Software” tab.
3. Click the “Add Site…” button and set the “Location” field to the ADT download site:https://dl-ssl.google.com/android/eclipse/. Click the “OK” button to add the site.You should now see the corresponding entry in the “Available Software” list as shownin Figure 2-2.
4. Expand the added entry by selecting the node in the list. You should see an entry named “Developer Tools” with two child nodes: “Android Development Tools” and “Android Editors.” Select the parent node “Developer Tools” and click the “Install” button to install ADT.
Eclipse will then download ADT and install it. You’ll need to restart Eclipse for the new plug-in to show up in the IDE. The final step to get ADT functional is to point it to the Android SDK. Select the Window menu and choose Preferences. In the “Preferences” dialog box, select the “Android” node and set the “SDK Location” field to the path of the Android SDK (see Figure 2-3). Then click the “OK” button. Note that you might see a dialog box asking if you want to send usage statistics to Google concerning the Android SDK.
You are almost ready for your first Android application—we have to briefly discuss the fundamental concepts of an Android application first.
Android Service Components
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("http://192.178.10.131/WS2/Upload.aspx");
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 origi-nally designed as part of Java API 1.4; you can read more about it at the following Java site:
http://java.sun.com/j2se/1.4.2/docs/guide/imf/overview.html
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 mani-fest file (AndroidManifest.xml). Here is an example:
android:versionCode="1"
android:versionName="1.0.0">
The Android manifest file is where activities are defined, where services and content pro-viders 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 impor-tant Java packages that are included in the Android SDK:
• android.app: 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).
• android.content.pm: Implements Package Manager–related classes. A package man-ager 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 SQLiteCursor, SQLiteDatabase, SQLiteQuery, SQLiteQueryBuilder, and SQLiteStatement. However, most of your inter-action is going to be with classes from the abstract android.database package.
• android.graphics: Contains the classes Bitmap, Canvas, Camera, Color, Matrix, Movie,Paint, Path, Rasterizer, Shader, SweepGradient, and TypeFace.
• android.graphics.drawable: Implements drawing protocols and background images, and allows animation of drawable objects.
• android.graphics.drawable.shapes: Implements shapes including ArcShape, OvalShape, PathShape, RectShape, and RoundRectShape.
• android.hardware: Implements the physical Camera-related classes. This Camera repre-sents the hardware camera, whereas android.graphics.Camera represents a graphical concept that’s not related to a physical camera at all.
•android.inputmethodservice: Implements the interfaces and base abstract classes nec-essary 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.
•android.media: 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 notifica-
tions. AudioManager is responsible for volume controls. You can use FaceDetector to detect people’s faces in a bitmap.
•android.net: Implements the basic socket-level network APIs. Primary classes include Uri, ConnectivityManager, LocalSocket, and LocalServerSocket.
•android.net.wifi: 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 pri-mary 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 lan-guage. 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 meta-data 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.
•android.text.style: 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.
•com.google.android.maps: 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 util.zip.
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 applica-tions for handheld devices.
Taking Advantage of Android Source Code
During these early releases of Android, documentation is a bit “wanting” in places. When you run into that situation, it is worthwhile exploring Android source code to fill the gaps.
As indicated, Android is a platform and not just one project. You can see the scope and the number of projects at http://source.android.com/projects.
The source code of Android and all its projects is managed by the Git source-code control system. Git (http://git.or.cz/) is an open source source-control system designed to handle large and small projects with speed and convenience. The Linux kernel and Ruby on Rails projects also rely on Git for version control. The complete list of Android projects in the Git repository appears at http://android.git.kernel.org/.
You can download any of these projects using the tools provided by Git and described at the product’s web site. Some of the primary projects include Dalvik, frameworks/base (the android.jar file), Linux kernel, and a number of external libraries such as Apache HTTP librar-ies (apache-http). The core Android applications are also hosted here. Some of these core applications include: AlarmClock, Browser, Calculator, Calendar, Camera, Contacts, Email, GoogleSearch, HTML Viewer, IM, Launcher, Mms, Music, PackageInstaller, Phone, Settings,SoundRecorder, Stk, Sync, Updater, and VoiceDialer.
The Android projects also include the “Provider” projects. “Provider” projects are like databases in Android that wrap their data into RESTful services. These projects are Calen-darProvider, ContactsProvider, DownloadProvider, DrmProvider, GoogleContactsProvider, GoogleSubscribedFeedsProvider, ImProvider, MediaProvider, SettingsProvider, Subscribed-FeedsProvider, and TelephonyProvider.
As a programmer, you will be most interested in the source code that makes up the android.jar file. (If you’d rather download the entire platform and build it yourself, refer to the documentation available at http://source.android.com/download.) You can download the source for this .jar file by typing in the following URL:
http://git.source.android.com/
?p=platform/frameworks/base.git;a=snapshot;h=HEAD;sf=tgz
This is one of the general-purpose URLs you can use to download Git projects. On Win-dows, you can unzip this file using pkzip. Although you can download and unzip the source, it might be more convenient to just look at these files online if you don’t need to debug the source code through your IDE. Git also allows you to do this. For example, you can browse through android.jar source files by visiting this URL:
http://android.git.kernel.org/?p=platform/frameworks/base.git;a=summary
However, you have to do some work after you visit this page. Pick grep from the drop-down list and enter some text in the search box. Click one of the resulting file names to open that source file in your browser. This facility is convenient for a quick lookup of source code.
At times the file you are looking for might not be in the frameworks/base directory or proj-ect. In that case, you need to find the list of projects and search each one step by step. The URL for this list is http://android.git.kernel.org/.
You cannot grep across all projects, so you will need to know which project belongs to which facility in Android. For example, the graphics-related libraries in the Skia project are available here:
http://android.git.kernel.org/?p=platform/external/skia.git;a=summary
Developing an End-User Application with the Android SDK
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, head- phones, battery simulation, and Bluetooth.
The Android emulator accomplishes its work through an open source “processor emula-tor” technology called QEMU (http://bellard.org/qemu/) developed by Fabrice Bellard. This is the same technology that allows emulation of one operating system on top of another, irre-spective 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 archi-tecture. 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 approxi-mately 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 http://code.google.com/android/reference/emulator.html.
The Android UI
Android uses a UI framework that resembles other desktop-based, full-featured UI frame-works, 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, introduc-ing 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.
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 logi-cal 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 win-dows. 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.15
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);
intent.setData(Uri.parse("http://www.google.com"));
activity.startActivity(intent);
}
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 gen-erated IDs instead. This indirection helps a great deal when it comes to localization. (Chapter 3 covers the R.java file and resources in more detail.)
Another new concept in Android is the content provider. A content provider is an abstrac-tion 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 appli-cation 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:
android:text="@string/hello"
/>
You will then use an ID generated for this XML file to load this layout into an activity win-dow. (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:
Although Android supports dialogs, all dialogs in Android are asynchronous. These asynchronous dialogs present a special challenge to developers accustomed to the synchro-nous 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 asyn-chronous-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. More-over, 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:
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. More-
over, 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:
……
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 anima-tion 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
famil-iar 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 begin-ning 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.
Introducing the Android Computing Platform
We are also expecting a surge in mobile programming in the IT industry as more and more IT applications start to offer mobile counterparts. To help you profit from this trend, we’llshow you how to use Java to write programs for devices that run on Google’s Android Platform (http://code.google.com/android/), an open source platform for mobile development. We are excited about Android because it is an advanced platform that introduces a number of new paradigms in framework design. In this chapter, we’ll provide an overview of Android and itsSDK, show you how to take advantage of Android source code, and highlight the benefits of programming for the Android Platform.
The fact that hitherto dedicated devices such as mobile phones can now count them-selves among other venerable general-computing platforms is great news for programmers(see Figure 1-1). This new trend makes mobile devices accessible through general-purpose com-puting languages and therefore increases the range and market share for mobile applications.
The Android Platform fully embraces this idea of general-purpose computing for hand-held devices. It is indeed a comprehensive platform that features a Linux-based operatingsystem stack for managing devices, memory, and processes. Android’s libraries cover tele-phony, video, graphics, UI programming, and every other aspect of the physical device.
The Android Platform, although built for mobile devices, exhibits the characteristics of afull-featured desktop framework. Google makes this framework available to Java programmersthrough a software development kit called the Android SDK. When you are working with theAndroid SDK, you rarely feel that you are writing to a mobile device because you have access tomost of the class libraries that you use on a desktop or a server—including a relational database.
The Android SDK supports most of Java Platform, Standard Edition (Java SE) except for theAbstract Window Toolkit (AWT) and Swing. In place of the AWT and Swing, the Android SDKhas its own extensive modern UI framework. Because you’re programming your applications inJava, you might expect to need a Java Virtual Machine (JVM) that is responsible for interpretingthe runtime Java bytecode. A JVM typically provides necessary optimization to help Java reachperformance levels comparable to compiled languages such as C and C++. Android offers itsown optimized JVM to run the compiled Java class files in order to counter the handheld devicelimitations such as memory, processor speed, and power. This virtual machine is called theDalvik VM, which we’ll explore in the section “Delving Into the Dalvik VM.”
The familiarity and simplicity of the Java programming language coupled with Android’sextensive class library makes Android a compelling platform to write programs for. Figure 1-2 provides an overview of the Android software stack. (We’ll provide further details in the sec-tion “Understanding the Android Software Stack.”)
History of Android
Now that we’ve provided a brief introduction to the Android Platform, we’ll describe how it appeared on the mobile-development scene. Mobile phones use a variety of operating systems such as Symbian OS, Microsoft’s Windows Mobile, Mobile Linux, iPhone OS (based on Mac OS X), and many other proprietary OSs. Supporting standards and publishing APIs would greatly encourage widespread, low-cost development of mobile applications, but none of these OSs has taken a clear lead in doing so. Then Google entered the space with its Android Platform, promising openness, affordability, open source code, and a high-end development framework.
Google acquired the startup company Android Inc. in 2005 to start the development of the Android Platform (see Figure 1-3). The key players at Android Inc. included Andy Rubin, Rich Miner, Nick Sears, and Chris White.
In late 2007, a group of industry leaders came together around the Android Platform to form the Open Handset Alliance (http://www.openhandsetalliance.com). Some of the alli-ance’s prominent members include
Part of the alliance’s goal is to innovate rapidly and respond better to consumer needs, and its first key outcome was the Android Platform. Android was designed to serve the needs of mobile operators, handset manufacturers, and application developers. The members have committed to release significant intellectual property through the open source Apache License, Version 2.0.
The Android SDK was first issued as an “early look” release in November 2007. In Septem-ber 2008, T-Mobile announced the availability of the T-Mobile G1, the first smartphone based on the Android Platform. A few days after that, Google announced the availability of Android SDK Release Candidate 1.0. In October 2008, Google made the source code of the Android Platform available under Apache’s open source license.
When Android was released, one of its key architectural goals was to allow applications to interact with one another and reuse components from one another. This reuse not only applies to services, but also to data and UI. As a result, the Android Platform has a number of architectural features that keep this openness a reality. We’ll delve into some of these features in Chapter 3.
Android has also attracted an early following because of its fully developed features to exploit the cloud-computing model offered by web resources and to enhance that experience with local data stores on the handset itself. Android’s support for a relational database on the handset also played a part in early adoption.
In late 2008 Google released a handheld device called Android Dev Phone 1 that is capable of running Android applications without being tied to any cell phone provider network. The goal of this device (approximate cost $400.00) is to allow developers to experiment with a real device that can run the Android OS with out any contracts. At around the same time, Google also released a bug fix version 1.1 of the OS that is solely based on 1.0. In releases 1.0 and 1.1 Android did not support soft keyboards, requiring the devices to carry physical keys. Android fixed this issue by releasing the 1.5 SDK in April of 2009, along with a number of other features, such as advanced media-recording capabilities, widgets, and live folders. The last two chapters of this book are dedicated to exploring the features from this 1.5 SDK
Delving into the Dalvik VM
Google has spent a lot of time thinking about optimizing designs for low-powered handhelddevices. Handheld devices lag behind their desktop counterparts in memory and speed by eight to ten years. They also have limited power for computation; a handheld device’s total RAM might be as little as 64MB, and its available space for applications might be as little as 20MB.
The performance requirements on handsets are severe as a result, requiring handset designers to optimize everything. If you look at the list of packages in Android, you’ll see that they are full-featured and extensive in number. According to Google, these system libraries might use as much as 10MB, even with their optimized JVM.
These issues led Google to revisit the standard JVM implementation in many respects.(The key figure in Google’s implementation of this JVM is Dan Bornstein, who wrote the Dalvik VM and named it after a town in Iceland.) First, the Dalvik VM takes the generated Java class files and combines them into one or more Dalvik Executable (.dex) files. It reuses duplicate information from multiple class files, effectively reducing the space requirement (uncom- pressed) by half from a traditional .jar file. For example, the .dex file of the web-browser app in Android is about 200K, whereas the equivalent uncompressed.jar version is about 500K. The .dex file of the alarm-clock app is about 50K, and roughly twice that size in its .jar version.
Second, Google has fine-tuned the garbage collection in the Dalvik VM, but it has cho-sen to omit a just-in-time (JIT) compiler, in this release at least. The company can justify this choice because many of Android’s core libraries, including the graphics libraries, are imple-mented in C and C++. For example, the Java graphics APIs are actually thin wrapper classes around the native code using the Java Native Interface (JNI). Similarly, Android provides an optimized C-based native library to access the SQLite database, but this library is encapsulated in a higher-level Java API. Because most of the core code is in C and C++, Google reasoned that the impact of JIT compilation would not be significant.
Finally, the Dalvik VM uses a different kind of assembly-code generation, in which it uses registers as the primary units of data storage instead of the stack. Google is hoping to accom-plish 30 percent fewer instructions as a result.
We should point out that the final executable code in Android, as a result of the Dalvik VM, is based not on Java bytecode but on .dex files instead. This means you cannot directly execute Java bytecode; you have to start with Java class files and then convert them to linkable .dex files.
This extreme performance paranoia extends into the rest of the Android SDK. For exam-ple, the Android SDK uses XML extensively to define UI layouts. However, all of this XML is compiled to binary files before these binary files become resident on the devices. Android provides special mechanisms to use this XML data.
While we are on the subject of Android’s design considerations, we should answer this question: How would one compare and contrast Android to Java Platform, Micro Edition (Java ME)?
Comparing Android and Java ME
As you have seen so far in this chapter, Android has taken a dedicated and focused approach to its mobile-platform efforts that goes beyond a simple JVM-based solution. The Android Plat-form comes with everything you need in a single package: the OS, device drivers, core libraries,the JNI, the optimized Dalvik VM, and the Java development environment. Developers can be assured that when they develop new applications, all key libraries will be available on the device.
Let us offer a brief overview of Java ME before comparing the two approaches. Figure 1-4 shows the availability of Java for various computing configurations. Java Platform, Standard Edition (Java SE) is suitable for desktop and workstation configurations. Java Platform, Enter-prise Edition (Java EE) is designed for server configurations.
Java Platform, Micro Edition (Java ME) is an edition of Java that is pared down for smaller devices. Furthermore, two configuration sets are available for Java ME. The first configura- tion is called the Connected Device Configuration (CDC). Java ME for CDC involves a pared down version of Java SE with fewer packages, fewer classes within those packages, and even
fewer fields and methods within those classes. For appliances and devices that are further con-strained, Java defines a configuration called Connected Limited Device Configuration (CLDC).The available APIs for various Java configurations are contrasted in Figure 1-5.
Any optional packages that are installed on top of the base CDC and CLDC APIs are treated as “profiles” that are standardized using the JSR process. Each defined profile makes an additional set of APIs available to the developer.
The CLDC Java platform is hosted on a specialized and much reduced JVM called the K Virtual Machine (KVM), which is capable of running on devices whose memory is as low as 128K. (The “K” in “KVM” stands for “kilobytes.”) CLDC can run additional APIs under MIDP (Mobile Information Device Profile) 2.0. This API includes a number of packages under javax.microedition.*. The key packages are MIDlets (simple applications), a UI package called LCDUI, gaming, and media.
The CDC configuration APIs include the java.awt API, the java.net API, and more secu-rity APIs in addition to the CLDC configuration APIs. The additional profiles available on top of CDC make the javax.microedition.xlet API available to application programmers (Xlets represent applications in the CDC configuration). On top of a CDC configuration you’ll find about ten more optional packages that you can run, including Bluetooth, Media API, OpenGL for Embedded Systems (OpenGL ES), Java API for XML Processing (JAXP), JAXP-RPC, Java 2D, Swing, Java Remote Method Invocation (Java RMI), and Java Database Connectivity {JDBC). Overall the Java ME specification includes more than 20 JSRs. It is also expected that JavaFX (http://javafx.com) will play an increasing role in the mobile space for Java.
Now that you have a background on Java ME, look at how it compares to Android
Multiple device configurations: Java ME addresses two classes of micro devices and offers standardized and distinct solutions for each. Android, on the other hand, applies to just one model. It won’t run on low-end devices unless or until the configurations of those devices improve.
Ease of understanding: Because Android is geared toward only one device model, it’s easier to understand than Java ME. Java ME has multiple UI models for each configura-tion, depending on the features supported by the device: MIDlets, Xlets, the AWT, and Swing. The JSRs for each Java ME specification are harder to follow; they take longer to mature; and finding implementations for them can be difficult.
Responsiveness: The Dalvik VM is more optimized and more responsive compared to the standard JVM supported on a similarly configured device. You can compare the Dalvik VM to the KVM, but the KVM addresses a lower-level device with much less memory
Java compatibility: Because of the Dalvik VM, Android runs .dex bytecode instead of Java bytecode. This should not be a major concern as long as Java is compiled to stan-dard Java class files. Only runtime interpretation of Java bytecode is not possible.
Adoption: There is widespread support for Java ME on mobile devices because most mobile phones support it. But the uniformity, cost, and ease of development in Android are compelling reasons for Java developers to program for it.
Java SE support: Compared to the support for Java SE in CDC, the Android support for Java SE is a bit more complete, except for the AWT and Swing. As we mentioned earlier,Android has its own UI approach instead. In fact, Android’s declarative UI resembles the JavaFX approach.
Understanding the Android Software Stack
So far we’ve covered Android’s history and its optimization features including the Dalvik VM,and we’ve hinted at the Java programming stack available. In this section, we would like to cover the development aspect of Android. Figure 1-6 is a good place to start this discussion.
At the core of the Android Platform is Linux kernel version 2.6, responsible for device driv-ers, resource access, power management, and other OS duties. The supplied device drivers include Display, Camera, Keypad, WiFi, Flash Memory, Audio, and IPC (interprocess com-munication). Although the core is Linux, the majority—if not all—of the applications on an Android device such as the T-Mobile G1 are developed in Java and run through the Dalvik VM.
Sitting at the next level, on top of the kernel, are a number of C/C++ libraries such as OpenGL, WebKit, FreeType, Secure Sockets Layer (SSL), the C runtime library (libc), SQLite,and Media. The system C library based on Berkeley Software Distribution (BSD) is tuned (to roughly half its original size) for embedded Linux-based devices. The media libraries are based on PacketVideo’s (http://www.packetvideo.com/) OpenCORE. These libraries are responsible for recording and playback of audio and video formats. A library called Surface Manager con-trols access to the display system and supports 2D and 3D.
The WebKit library is responsible for browser support; it is the same library that supports Google Chrome and Apple Inc.’s Safari. The FreeType library is responsible for font support.SQLite (http://www.sqlite.org/) is a relational database that is available on the device itself.SQLite is also an independent open source effort for relational databases and not directly tied to Android. You can acquire and use tools meant for SQLite for Android databases as well.
Most of the application framework accesses these core libraries through the Dalvik VM, the gateway to the Android Platform. As we indicated in the previous sections, Dalvik is opti-mized to run multiple instances of VMs. As Java applications access these core libraries, each application gets its own VM instance. The Dalvik VM is backward-compatible with Java SE Development Kit (JDK) 5.0 but optimized for the Android Platform. However, some features of the Java experience might differ because the version of Java SE on Android is a subset of the full platform.
The Android Java API’s main libraries include telephony, resources, locations, UI, con-tent providers (data), and package managers (installation, security, and so on). Programmers develop end-user applications on top of this Java API. Some examples of end-user applications on the device include Home, Contacts, Phone, Browser, and so on.
Android also supports a custom Google 2D graphics library called Skia, which is written in C and C++. Skia also forms the core of the Google Chrome browser. The 3D APIs in Android, however, are based on an implementation of OpenGL ES from the Khronos group (http://www.khronos.org). OpenGL ES contains subsets of OpenGL that are targeted toward embedded systems.
From a media perspective, the Android Platform supports the most common formats for audio, video, and images. From a wireless perspective, Android has APIs to support Bluetooth,EDGE, 3G, WiFi, and Global System for Mobile Communication (GSM) telephony, depending on the hardware.
Recent Posts
-
Compiled and Noncompiled Android Resources
-
Using resources, Content Providers, and Intents
-
Examining the Application Lifecycle
-
Exploring the Structure of an Android Application
-
Learning the Fundamental Components
-
Getting Your Feet Wet
-
Android Service Components
-
Developing an End-User Application with the Android SDK
-
Introducing the Android Computing Platform
-
Setting up a Successful Website