Hello, Android - Professional Android 4 Application Development (2012)

Professional Android 4 Application Development (2012)

Chapter 1. Hello, Android

What's in this Chapter?

A background of mobile application development

What Android is (and what it isn't)

An introduction to the Android SDK features

Which devices Android runs on

Why you should develop for mobile and Android

An introduction to the Android SDK and development framework

Whether you're an experienced mobile engineer, a desktop or web developer, or a complete programming novice, Android represents an exciting new opportunity to write innovative applications for an increasingly wide range of devices.

Despite the name, Android will not help you create an unstoppable army of emotionless robot warriors on a relentless quest to cleanse the earth of the scourge of humanity. Instead, Android is an open-source software stack that includes the operating system, middleware, and key mobile applications, along with a set of API libraries for writing applications that can shape the look, feel, and function of the devices on which they run.

Small, stylish, and versatile, modern mobile devices have become powerful tools that incorporate touchscreens, cameras, media players, Global Positioning System (GPS) receivers, and Near Field Communications (NFC) hardware. As technology has evolved, mobile phones have become about much more than simply making calls. With the introduction of tablets and Google TV, Android has expanded beyond its roots as a mobile phone operating system, providing a consistent platform for application development across an increasingly wide range of hardware.

In Android, native and third-party applications are written with the same APIs and executed on the same run time. These APIs feature hardware access, video recording, location-based services, support for background services, map-based activities, relational databases, inter-application communication, Bluetooth, NFC, and 2D and 3D graphics.

This book describes how to use these APIs to create your own Android applications. In this chapter you'll learn some guidelines for mobile and embedded hardware development, as well as be introduced to some of the platform features available for Android development.

Android has powerful APIs, excellent documentation, a thriving developer community, and no development or distribution costs. As mobile devices continue to increase in popularity, and Android devices expand into exciting new form-factors, you have the opportunity to create innovative applications no matter what your development experience.

A Little Background

In the days before Twitter and Facebook, when Google was still a twinkle in its founders' eyes and dinosaurs roamed the earth, mobile phones were just that—portable phones small enough to fit inside a briefcase, featuring batteries that could last up to several hours. They did, however, offer the freedom to make calls without being physically connected to a landline.

Increasingly small, stylish, and powerful, mobile phones are now ubiquitous and indispensable. Hardware advancements have made mobiles smaller and more efficient while featuring bigger, brighter screens and including an increasing number of hardware peripherals.

After first including cameras and media players, mobiles now feature GPS receivers, accelerometers, NFC hardware, and high-definition touchscreens. These hardware innovations offer fertile ground for software development, but until relatively recently the applications available for mobile phones have lagged behind their hardware counterparts.

The Not-So-Distant Past

Historically, developers, generally coding in low-level C or C++, have needed to understand the specific hardware they were coding for, typically a single device or possibly a range of devices from a single manufacturer. As hardware technology and mobile Internet access has advanced, this closed approach has become outmoded.

Platforms such as Symbian were later created to provide developers with a wider target audience. These systems proved more successful in encouraging mobile developers to provide rich applications that better leveraged the hardware available.

Although these platforms did, and continue to, offer some access to the device hardware, they generally required developers to write complex C/C++ code and make heavy use of proprietary APIs that are notoriously difficult to work with. This difficulty is amplified for applications that must work on different hardware implementations and those that make use of a particular hardware feature, such as GPS.

In more recent years, the biggest advance in mobile phone development was the introduction of Java-hosted MIDlets. MIDlets are executed on a Java virtual machine (JVM), a process that abstracts the underlying hardware and lets developers create applications that run on the wide variety of devices that support the Java run time. Unfortunately, this convenience comes at the price of restricted access to the device hardware.

In mobile development, it was long considered normal for third-party applications to receive different hardware access and execution rights from those given to native applications written by the phone manufacturers, with MIDlets often receiving few of either.

The introduction of Java MIDlets expanded developers' audiences, but the lack of low-level hardware access and sandboxed execution meant that most mobile applications were regular desktop programs or websites designed to render on a smaller screen, and didn't take advantage of the inherent mobility of the handheld platform.

Living in the Future

Android sits alongside a new wave of modern mobile operating systems designed to support application development on increasingly powerful mobile hardware. Platforms like Microsoft's Windows Phone and the Apple iPhone also provide a richer, simplified development environment for mobile applications; however, unlike Android, they're built on proprietary operating systems. In some cases they prioritize native applications over those created by third parties, restrict communication among applications and native phone data, and restrict or control the distribution of third-party applications to their platforms.

Android offers new possibilities for mobile applications by offering an open development environment built on an open-source Linux kernel. Hardware access is available to all applications through a series of API libraries, and application interaction, while carefully controlled, is fully supported.

In Android, all applications have equal standing. Third-party and native Android applications are written with the same APIs and are executed on the same run time. Users can remove and replace any native application with a third-party developer's alternative; indeed, even the dialer and home screens can be replaced.

What Android Isn't

As a disruptive addition to a mature field, it's not hard to see why there has been some confusion about what exactly Android is. Android is not the following:

· A Java ME implementation—Android applications are written using the Java language, but they are not run within a Java ME (Mobile Edition) VM, and Java-compiled classes and executables will not run natively in Android.

· Part of the Linux Phone Standards Forum (LiPS) or the Open Mobile Alliance (OMA)—Android runs on an open-source Linux kernel, but, while their goals are similar, Android's complete software stack approach goes further than the focus of these standards-defining organizations.

· Simply an application layer (such as UIQ or S60)—Although Android does include an application layer, “Android” also describes the entire software stack, encompassing the underlying operating system, the API libraries, and the applications themselves.

· A mobile phone handset—Android includes a reference design for mobile handset manufacturers, but there is no single “Android phone.” Instead, Android has been designed to support many alternative hardware devices.

· Google's answer to the iPhone—The iPhone is a fully proprietary hardware and software platform released by a single company (Apple), whereas Android is an open-source software stack produced and supported by the Open Handset Alliance (OHA) and designed to operate on any compatible device.

Android: An Open Platform for Mobile Development

Google's Andy Rubin describes Android as follows:

The first truly open and comprehensive platform for mobile devices. It includes an operating system, user-interface and applications—all of the software to run a mobile phone but without the proprietary obstacles that have hindered mobile innovation.

—Where's My Gphone? (http://googleblog.blogspot.com/2007/11/wheres-my-gphone.html)

More recently, Android has expanded beyond a pure mobile phone platform to provide a development platform for an increasingly wide range of hardware, including tablets and televisions.

Put simply, Android is an ecosystem made up of a combination of three components:

· A free, open-source operating system for embedded devices

· An open-source development platform for creating applications

· Devices, particularly mobile phones, that run the Android operating system and the applications created for it

More specifically, Android is made up of several necessary and dependent parts, including the following:

· A Compatibility Definition Document (CDD) and Compatibility Test Suite (CTS) that describe the capabilities required for a device to support the software stack.

· A Linux operating system kernel that provides a low-level interface with the hardware, memory management, and process control, all optimized for mobile and embedded devices.

· Open-source libraries for application development, including SQLite, WebKit, OpenGL, and a media manager.

· A run time used to execute and host Android applications, including the Dalvik Virtual Machine (VM) and the core libraries that provide Android-specific functionality. The run time is designed to be small and efficient for use on mobile devices.

· An application framework that agnostically exposes system services to the application layer, including the window manager and location manager, databases, telephony, and sensors.

· A user interface framework used to host and launch applications.

· A set of core pre-installed applications.

· A software development kit (SDK) used to create applications, including the related tools, plug-ins, and documentation.

What really makes Android compelling is its open philosophy, which ensures that you can fix any deficiencies in user interface or native application design by writing an extension or replacement. Android provides you, as a developer, with the opportunity to create mobile phone interfaces and applications designed to look, feel, and function exactly as you imagine them.

Native Android Applications

Android devices typically come with a suite of preinstalled applications that form part of the Android Open Source Project (AOSP), including, but not necessarily limited to, the following:

· An e-mail client

· An SMS management application

· A full PIM (personal information management) suite, including a calendar and contacts list

· A WebKit-based web browser

· A music player and picture gallery

· A camera and video recording application

· A calculator

· A home screen

· An alarm clock

In many cases Android devices also ship with the following proprietary Google mobile applications:

· The Google Play Store for downloading third-party Android applications

· A fully featured mobile Google Maps application, including StreetView, driving directions, and turn-by-turn navigation, satellite views, and traffic conditions

· The Gmail email client

· The Google Talk instant-messaging client

· The YouTube video player

The data stored and used by many of these native applications—such as contact details—are also available to third-party applications. Similarly, your applications can respond to events such as incoming calls.

The exact makeup of the applications available on new Android phones is likely to vary based on the hardware manufacturer and/or the phone carrier or distributor.

The open-source nature of Android means that carriers and OEMs can customize the user interface and the applications bundled with each Android device. Several OEMs have done this, including HTC with Sense, Motorola with MotoBlur, and Samsung with TouchWiz.

It's important to note that for compatible devices, the underlying platform and SDK remain consistent across OEM and carrier variations. The look and feel of the user interface may vary, but your applications will function in the same way across all compatible Android devices.

Android SDK Features

The true appeal of Android as a development environment lies in its APIs.

As an application-neutral platform, Android gives you the opportunity to create applications that are as much a part of the phone as anything provided out-of-the-box. The following list highlights some of the most noteworthy Android features:

· GSM, EDGE, 3G, 4G, and LTE networks for telephony or data transfer, enabling you to make or receive calls or SMS messages, or to send and retrieve data across mobile networks

· Comprehensive APIs for location-based services such as GPS and network-based location detection

· Full support for applications that integrate map controls as part of their user interfaces

· Wi-Fi hardware access and peer-to-peer connections

· Full multimedia hardware control, including playback and recording with the camera and microphone

· Media libraries for playing and recording a variety of audio/video or still-image formats

· APIs for using sensor hardware, including accelerometers, compasses, and barometers

· Libraries for using Bluetooth and NFC hardware for peer-to-peer data transfer

· IPC message passing

· Shared data stores and APIs for contacts, social networking, calendar, and multi-media

· Background Services, applications, and processes

· Home-screen Widgets and Live Wallpaper

· The ability to integrate application search results into the system searches

· An integrated open-source HTML5 WebKit-based browser

· Mobile-optimized, hardware-accelerated graphics, including a path-based 2D graphics library and support for 3D graphics using OpenGL ES 2.0

· Localization through a dynamic resource framework

· An application framework that encourages the reuse of application components and the replacement of native applications

Access to Hardware, Including Camera, GPS, and Sensors

Android includes API libraries to simplify development involving the underlying device hardware. They ensure that you don't need to create specific implementations of your software for different devices, so you can create Android applications that work as expected on any device that supports the Android software stack.

The Android SDK includes APIs for location-based hardware (such as GPS), the camera, audio, network connections, Wi-Fi, Bluetooth, sensors (including accelerometers), NFC, the touchscreen, and power management. You can explore the possibilities of some of Android's hardware APIs in more detail in Chapters 12 and 15–17.

Data Transfers Using Wi-Fi, Bluetooth, and NFC

Android offers rich support for transferring data between devices, including Bluetooth, Wi-Fi Direct, and Android Beam. These technologies offer a rich variety of techniques for sharing data between paired devices, depending on the hardware available on the underlying device, allowing you to create innovative collaborative applications.

In addition, Android offers APIs to manage your network connections, Bluetooth connections, and NFC tag reading.


Details on using Android's communications APIs are available in Chapter 16, “Bluetooth, NFC, Networks, and Wi-Fi.”

Maps, Geocoding, and Location-Based Services

Embedded map support enables you to create a range of map-based applications that leverage the mobility of Android devices. Android lets you design user interfaces that include interactive Google Maps that you can control programmatically and annotate using Android's rich graphics library.

Android's location-based services manage technologies such as GPS and Google's network-based location technology to determine the device's current position. These services enforce an abstraction from specific location-detecting technology and let you specify minimum requirements (e.g., accuracy or cost) rather than selecting a particular technology. This also means your location-based applications will work no matter what technology the host device supports.

To combine maps with locations, Android includes an API for forward and reverse geocoding that lets you find map coordinates for an address, and the address of a map position.


You'll learn the details of using maps, the geocoder, and location-based services in Chapter 13, “Maps, Geocoding, and Location-Based Services.”

Background Services

Android supports applications and services designed to run in the background while your application isn't being actively used.

Modern mobiles and tablets are by nature multifunction devices; however, their screen sizes and interaction models mean that generally only one interactive application is visible at any time. Platforms that don't support background execution limit the viability of applications that don't need your constant attention.

Background services make it possible to create invisible application components that perform automatic processing without direct user action. Background execution allows your applications to become event-driven and to support regular updates, which is perfect for monitoring game scores or market prices, generating location-based alerts, or prioritizing and prescreening incoming calls and SMS messages.

Notifications are the standard means by which a mobile device traditionally alerts users to events that have happened in a background application. Using the Notification Manager, you can trigger audible alerts, cause vibration, and flash the device's LED, as well as control status bar notification icons.


Learn more about how to use Notifications and get the most out of background services in Chapters 9 and 10.

SQLite Database for Data Storage and Retrieval

Rapid and efficient data storage and retrieval are essential for a device whose storage capacity is relatively limited.

Android provides a lightweight relational database for each application via SQLite. Your applications can take advantage of this managed relational database engine to store data securely and efficiently.

By default, each application database is sandboxed—its content is available only to the application that created it—but Content Providers supply a mechanism for the managed sharing of these application databases as well as providing an abstraction between your application and the underlying data source.


Databases and Content Providers are covered in detail in Chapter 8, “Databases and Content Providers.”

Shared Data and Inter-Application Communication

Android includes several techniques for making information from your applications available for use elsewhere, primarily: Intents and Content Providers.

Intents provide a mechanism for message-passing within and between applications. Using Intents, you can broadcast a desired action (such as dialing the phone or editing a contact) systemwide for other applications to handle. Using the same mechanism, you can register your own application to receive these messages or execute the requested actions.

You can use Content Providers to provide secure, managed access to your applications' private databases. The data stores for native applications, such as the contact manager, are exposed as Content Providers so you can read or modify this data from within your own applications.


Intents are a fundamental component of Android and are covered in depth in Chapter 5, “Intents and Broadcast Receivers.”

Chapter 8 covers content providers in detail, including the native providers, and demonstrates how to create and use providers of your own.

Using Widgets and Live Wallpaper to Enhance the Home Screen

Widgets and Live Wallpaper let you create dynamic application components that provide a window into your applications, or offer useful and timely information, directly on the home screen.

Offering a way for users to interact with your application directly from the home screen increases user engagement by giving them instant access to interesting information without needing to open the application, as well as adding a dynamic shortcut into your application from their home screen.


You'll learn how to create application components for the home screen in Chapter 14, “Invading the Home Screen.”

Extensive Media Support and 2D/3D Graphics

Bigger screens and brighter, higher-resolution displays have helped make mobiles multimedia devices. To help you make the most of the hardware available, Android provides graphics libraries for 2D canvas drawing and 3D graphics with OpenGL.

Android also offers comprehensive libraries for handling still images, video, and audio files, including the MPEG4, H.264, HTTP Live Streaming, VP8, WEBP, MP3, AAC, AMR, HLS, JPG, PNG, and GIF formats.


2D and 3D graphics are covered in depth in Chapter 11, “Advanced User Experience,” and Android media management libraries are covered in Chapter 15, “Audio, Video, and Using the Camera.”

Cloud to Device Messaging

The Android Cloud to Device Messaging (C2DM) service provides an efficient mechanism for developers to create event-driven applications based on server-side pushes.

Using C2DM you can create a lightweight, always-on connection between your mobile application and your server, allowing you to send small amounts of data directly to your device in real time.

The C2DM service is typically used to prompt applications of new data available on the server, reducing the need for polling, decreasing the battery impact of an application's updates, and improving the timeliness of those updates.

Optimized Memory and Process Management

Like Java and .NET, Android uses its own run time and VM to manage application memory. Unlike with either of these other frameworks, the Android run time also manages the process lifetimes. Android ensures application responsiveness by stopping and killing processes as necessary to free resources for higher-priority applications.

In this context, the highest priority is given to the application with which the user is interacting. Ensuring that your applications are prepared for a swift death but are still able to remain responsive, and to update or restart in the background if necessary, is an important consideration in an environment that does not allow applications to control their own lifetimes.


You will learn more about the Android application lifecycle in Chapter 3, “Creating Applications and Activities.”

Introducing the Open Handset Alliance

The Open Handset Alliance (OHA) is a collection of more than 80 technology companies, including hardware manufacturers, mobile carriers, software developers, semiconductor companies, and commercialization companies. Of particular note are the prominent mobile technology companies, including Samsung, Motorola, HTC, T-Mobile, Vodafone, ARM, and Qualcomm. In their own words, the OHA represents the following:

A commitment to openness, a shared vision for the future, and concrete plans to make the vision a reality. To accelerate innovation in mobile and offer consumers a richer, less expensive, and better mobile experience.


The OHA hopes to deliver a better mobile software experience for consumers by providing the platform needed for innovative mobile development at a faster rate and with higher quality than existing platforms, without licensing fees for either software developers or handset manufacturers.

What Does Android Run On?

The first Android mobile handset, the T-Mobile G1, was released in the United States in October 2008. By the beginning of 2012, more than 300 million Android-compatible devices have been sold from more than 39 manufacturers, in more than 123 countries, on 231 different carrier networks.

Rather than being a mobile OS created for a single hardware implementation, Android is designed to support a large variety of hardware platforms, from smartphones to tablets and televisions.

With no licensing fees or proprietary software, the cost to handset manufacturers for providing Android devices is comparatively low. Many people now expect that the advantages of Android as a platform for creating powerful applications will encourage device manufacturers to produce increasingly diverse and tailored hardware.

Why Develop for Mobile?

In market terms, the emergence of modern mobile smartphones—multifunction devices including a phone but featuring a full-featured web browser, cameras, media players, Wi-Fi, and location-based services—has fundamentally changed the way people interact with their mobile devices and access the Internet.

Mobile-phone ownership easily surpasses computer ownership in many countries, with more than 3 billion mobile phone users worldwide. 2009 marked the year that more people accessed the Internet for the first time from a mobile phone rather than a PC. Many people believe that within the next 5 years more people will access the Internet by mobile phone rather than using personal computers.

The increasing popularity of modern smartphones, combined with the increasing availability of high-speed mobile data and Wi-Fi hotspots, has created a huge opportunity for advanced mobile applications.

The ubiquity of mobile phones, and our attachment to them, makes them a fundamentally different platform for development from PCs. With a microphone, camera, touchscreen, location detection, and environmental sensors, a phone can effectively become an extra-sensory perception device.

Smartphone applications have changed the way people use their phones. This gives you, the application developer, a unique opportunity to create dynamic, compelling new applications that become a vital part of people's lives.

Why Develop for Android?

Android represents a clean break, a mobile framework based on the reality of modern mobile devices designed by developers, for developers.

With a simple, powerful, and open SDK, no licensing fees, excellent documentation, and a thriving developer community, Android represents an opportunity to create software that changes how and why people use their mobile phones.

The barrier to entry for new Android developers is minimal:

· No certification is required to become an Android developer.

· Google Play provides free, up-front purchase, and in-app billing options for distribution and monetization of your applications.

· There is no approval process for application distribution.

· Developers have total control over their brands.

From a commercial perspective, more than 850,000 new Android devices are activated daily, with many studies showing the largest proportion of new smartphone sales belonging to Android devices.

As of March 2012, Google Play (formerly Android Market) has expanded its support for application sales to 131 countries, supporting more than 10 billion installs at a growth rate of 1 billion downloads per month.

Factors Driving Android's Adoption

Developers have always been a critical element within the Android ecosystem, with Google and the OHA betting that the way to deliver better mobile software to consumers is to make it easier for developers to write it.

As a development platform, Android is powerful and intuitive, enabling developers who have never programmed for mobile devices to create innovative applications quickly and easily. It's easy to see how compelling Android applications have created demand for the devices necessary to run them, particularly when developers write applications for Android because they can't write them for other platforms.

As Android expands into more form-factors, with increasingly powerful hardware, advanced sensors, and new developer APIs, the opportunities for innovation will continue to grow.

Open access to the nuts and bolts of the underlying system is what's always driven software development and platform adoption. The Internet's inherent openness has seen it become the platform for a multibillion-dollar industry within 10 years of its inception. Before that, it was open systems such as Linux and the powerful APIs provided as part of the Windows operating system that enabled the explosion in personal computers and the movement of computer programming from the arcane to the mainstream.

This openness and power ensure that anyone with the inclination can bring a vision to life at minimal cost.

What Android Has That Other Platforms Don't Have

Many of the features listed previously, such as 3D graphics and native database support, are also available in other native mobile SDKs, as well as becoming available on mobile browsers.

The pace of innovation in mobile platforms, both Android and its competitors, makes an accurate comparison of the available features difficult. The following noncomprehensive list details some of the features available on Android that may not be available on all modern mobile development platforms:

· Google Maps applications—Google Maps for Mobile has been hugely popular, and Android offers a Google Map as an atomic, reusable control for use in your applications. The Map View lets you display, manipulate, and annotate a Google Map within your Activities to build map-based applications using the familiar Google Maps interface.

· Background services and applications—Full support for background applications and services lets you create applications based on an event-driven model, working silently while other applications are being used or while your mobile sits ignored until it rings, flashes, or vibrates to get your attention. Maybe it's a streaming music player, an application that tracks the stock market, alerting you to significant changes in your portfolio, or a service that changes your ringtone or volume depending on your current location, the time of day, and the identity of the caller. Android provides the same opportunities for all applications and developers.

· Shared data and inter-process communication—Using Intents and Content Providers, Android lets your applications exchange messages, perform processing, and share data. You can also use these mechanisms to leverage the data and functionality provided by the native Android applications. To mitigate the risks of such an open strategy, each application's process, data storage, and files are private unless explicitly shared with other applications via a full permission-based security mechanism, as detailed in Chapter 18, “Advanced Android Development.”

· All applications are created equal—Android doesn't differentiate between native applications and those developed by third parties. This gives consumers unprecedented power to change the look and feel of their devices by letting them completely replace every native application with a third-party alternative that has access to the same underlying data and hardware.

· Wi-Fi Direct and Android Beam—Using these innovative new inter-device communication APIs, you can include features such as instant media sharing and streaming. Android Beam is an NFC-based API that lets you provide support for proximity-based interaction, while Wi-Fi Direct offers a wider range peer-to-peer for reliable, high-speed communication between devices.

· Home-screen Widgets, Live Wallpaper, and the quick search box—Using Widgets and Live Wallpaper, you can create windows into your application from the phone's home screen. The quick search box lets you integrate search results from your application directly into the phone's search functionality.

The Changing Mobile Development Landscape

Existing mobile development platforms have created an aura of exclusivity around mobile development. In contrast, Android allows, even encourages, radical change.

As consumer devices, Android handsets ship with a core set of the standard applications that consumers expect on a new phone, but the real power lies in users' ability to completely customize their devices' look, feel, and function—giving application developers an exciting opportunity.

All Android applications are a native part of the phone, not just software that's run in a sandbox on top of it. Rather than writing small-screen versions of software that can be run on low-power devices, you can now build mobile applications that change the way people use their phones.

The field of mobile development is currently enjoying a period of rapid innovation and incredible growth. This provides both challenges and opportunities for developers simply to keep up with the pace of change, let alone identify the opportunities these changes make possible.

Android will continue to advance and improve to compete with existing and future mobile development platforms, but as an open-source developer framework, the strength of the SDK is very much in its favor. Its free and open approach to mobile application development, with total access to the phone's resources, represents an opportunity for any mobile developer looking to seize the opportunities now available in mobile development.

Introducing the Development Framework

With the “why” covered, let's take a look at the “how.”

Android applications normally are written using Java as the programming language but executed by means of a custom VM called Dalvik, rather than a traditional Java VM.


Later in this chapter you'll be introduced to the framework, starting with a technical explanation of the Android software stack, followed by a look at what's included in the SDK, an introduction to the Android libraries, and a look at the Dalvik VM.

Each Android application runs in a separate process within its own Dalvik instance, relinquishing all responsibility for memory and process management to the Android run time, which stops and kills processes as necessary to manage resources.

Dalvik and the Android run time sit on top of a Linux kernel that handles low-level hardware interaction, including drivers and memory management, while a set of APIs provides access to all the underlying services, features, and hardware.

What Comes in the Box

The Android SDK includes everything you need to start developing, testing, and debugging Android applications:

· The Android APIs—The core of the SDK is the Android API libraries that provide developer access to the Android stack. These are the same libraries that Google uses to create native Android applications.

· Development tools—The SDK includes several development tools that let you compile and debug your applications so that you can turn Android source code into executable applications. You will learn more about the developer tools in Chapter 2, “Getting Started.”

· The Android Virtual Device Manager and emulator—The Android emulator is a fully interactive mobile device emulator featuring several alternative skins. The emulator runs within an Android Virtual Device (AVD) that simulates a device hardware configuration. Using the emulator you can see how your applications will look and behave on a real Android device. All Android applications run within the Dalvik VM, so the software emulator is an excellent development environment—in fact, because it's hardware-neutral, it provides a better independent test environment than any single hardware implementation.

· Full documentation—The SDK includes extensive code-level reference information detailing exactly what's included in each package and class and how to use them. In addition to the code documentation, Android's reference documentation and developer guide explains how to get started, gives detailed explanations of the fundamentals behind Android development, highlights best practices, and provides deep-dives into framework topics.

· Sample code—The Android SDK includes a selection of sample applications that demonstrate some of the possibilities available with Android, as well as simple programs that highlight how to use individual API features.

· Online support—Android has rapidly generated a vibrant developer community. The Google Groups (http://developer.android.com/resources/community-groups .html#ApplicationDeveloperLists) are active forums of Android developers with regular input from the Android engineering and developer relations teams at Google. Stack Overflow (www.stackoverflow.com/questions/tagged/android) is also a hugely popular destination for Android questions and a great place to find answers to beginner questions.

For those of you using Eclipse, Android has released the Android Development Tools (ADT) plug-in that simplifies project creation and tightly integrates Eclipse with the Android emulator and the build and debugging tools. The features of the ADT plug-in are covered in more detail in Chapter 2.

Understanding the Android Software Stack

The Android software stack is, put simply, a Linux kernel and a collection of C/C++ libraries exposed through an application framework that provides services for, and management of, the run time and applications. The Android software stack is composed of the elements shown in Figure 1.1.

Figure 1.1


· Linux kernel—Core services (including hardware drivers, process and memory management, security, network, and power management) are handled by a Linux 2.6 kernel. The kernel also provides an abstraction layer between the hardware and the remainder of the stack.

· Libraries—Running on top of the kernel, Android includes various C/C++ core libraries such as libc and SSL, as well as the following:

· A media library for playback of audio and video media

· A surface manager to provide display management

· Graphics libraries that include SGL and OpenGL for 2D and 3D graphics

· SQLite for native database support

· SSL and WebKit for integrated web browser and Internet security

· Android run time—The run time is what makes an Android phone an Android phone rather than a mobile Linux implementation. Including the core libraries and the Dalvik VM, the Android run time is the engine that powers your applications and, along with the libraries, forms the basis for the application framework.

· Core libraries—Although most Android application development is written using the Java language, Dalvik is not a Java VM. The core Android libraries provide most of the functionality available in the core Java libraries, as well as the Android-specific libraries.

· Dalvik VM—Dalvik is a register-based Virtual Machine that's been optimized to ensure that a device can run multiple instances efficiently. It relies on the Linux kernel for threading and low-level memory management.

· Application framework—The application framework provides the classes used to create Android applications. It also provides a generic abstraction for hardware access and manages the user interface and application resources.

· Application layer—All applications, both native and third-party, are built on the application layer by means of the same API libraries. The application layer runs within the Android run time, using the classes and services made available from the application framework.

The Dalvik Virtual Machine

One of the key elements of Android is the Dalvik VM. Rather than using a traditional Java VM such as Java ME, Android uses its own custom VM designed to ensure that multiple instances run efficiently on a single device.

The Dalvik VM uses the device's underlying Linux kernel to handle low-level functionality, including security, threading, and process and memory management. It's also possible to write C/C++ applications that run closer to the underlying Linux OS. Although you can do this, in most cases there's no reason you should need to.

If the speed and efficiency of C/C++ is required for your application, Android provides a native development kit (NDK). The NDK is designed to enable you to create C++ libraries using the libc and libm libraries, along with native access to OpenGL.


This book focuses exclusively on writing applications that run within Dalvik using the SDK; NDK development is not within the scope of this book. If your inclinations run toward NDK development, exploring the Linux kernel and C/C++ underbelly of Android, modifying Dalvik, or otherwise tinkering with things under the hood, check out the Android Internals Google Group at http://groups.google.com/group/android-internals.

All Android hardware and system service access is managed using Dalvik as a middle tier. By using a VM to host application execution, developers have an abstraction layer that ensures they should never have to worry about a particular hardware implementation.

The Dalvik VM executes Dalvik executable files, a format optimized to ensure minimal memory footprint. You create .dex executables by transforming Java language compiled classes using the tools supplied within the SDK.


You'll learn more about how to create Dalvik executables in Chapter 2.

Android Application Architecture

Android's architecture encourages component reuse, enabling you to publish and share Activities, Services, and data with other applications, with access managed by the security restrictions you define.

The same mechanism that enables you to produce a replacement contact manager or phone dialer can let you expose your application's components in order to let other developers build on them by creating new UI front ends or functionality extensions.

The following application services are the architectural cornerstones of all Android applications, providing the framework you'll be using for your own software:

· Activity Manager and Fragment Manager—Control the lifecycle of your Activities and Fragments, respectively, including management of the Activity stack (described in Chapters 3 and 4).

· Views—Used to construct the user interfaces for your Activities and Fragments, as described in Chapter 4.

· Notification Manager—Provides a consistent and nonintrusive mechanism for signaling your users, as described in Chapter 10.

· Content Providers—Lets your applications share data, as described in Chapter 8.

· Resource Manager—Enables non-code resources, such as strings and graphics, to be externalized, as shown in Chapter 3.

· Intents—Provides a mechanism for transferring data between applications and their components, as described in Chapter 5.

Android Libraries

Android offers a number of APIs for developing your applications. Rather than list them all here, check out the documentation at http://developer.android.com/reference/packages.html, which gives a complete list of packages included in the Android SDK.

Android is intended to target a wide range of mobile hardware, so be aware that the suitability and implementation of some of the advanced or optional APIs may vary depending on the host device.