Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Android recipes
Nội dung xem thử
Mô tả chi tiết
COMPANION eBOOK
US $44.99
Shelve in
Mobile Computing
User level:
www.apress.com Intermediate
BOOKS FOR PROFESSIONALS BY PROFESSIONALS®
Android Recipes teaches you how to develop top-notch apps using a proven
problem-solution approach. First, a problem is identified. Then a clear explanation of the solution is given, supported by a fully worked code sample. Best of
all, you can apply all the code examples found in the book directly to your own
projects—saving you time and a great deal of work!
This new edition offers more than 100 down-to-earth recipes that will teach
you how to:
• Use external libraries to save time and effort
• Boost app performance by using the Android NDK and Renderscript
• Design apps for performance, responsiveness, and seamlessness
• Send data between devices and other external hardware
• Persist application data and share it between applications
• Capture and play back various device media items
• Communicate with web services
• Get the most out of your user interface
• Develop a unit conversion app in the context of the command-line/
Android SDK and Eclipse/Android SDK environments
Crammed with insightful instruction and helpful examples, this second edition of Android Recipes is your guide to writing apps for one of today’s hottest
mobile platforms. It offers pragmatic advice that will help you get the job done
quickly and well.
Dave Smith | Jeff Friesen
A valuable coding reference for creating
all kinds of Android apps
Companion
eBook
Available Smith Friesen Android Recipes
SOURCE CODE ONLINE
SECOND EDITION
SECOND
EDITION
Android Recipes
A Problem-Solution Approach
www.it-ebooks.info
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
www.it-ebooks.info
iii
Contents at a Glance
Foreword ................................................................................................... xviii
About the Authors........................................................................................ xix
About the Technical Reviewer ...................................................................... xx
Acknowledgments ....................................................................................... xxi
Preface ....................................................................................................... xxii
Chapter 1: Getting Started with Android............................................... 1
Chapter 2: User Interface Recipes....................................................... 99
Chapter 3: Communications and Networking ................................... 323
Chapter 4: Interacting with Device Hardware and Media................. 421
Chapter 5: Persisting Data ................................................................ 501
Chapter 6: Interacting with the System ............................................ 581
Chapter 7: Working with Libraries .................................................... 689
Chapter 8: Working with Android NDK and Renderscript ................. 743
Appendix A: Scripting Layer for Android........................................... 805
Appendix B: Android Tools Overview ................................................ 821
Appendix C: App Design Guidelines .................................................. 855
Appendix D: Univerter Architecture .................................................. 867
Index.................................................................................................. 911
www.it-ebooks.info
1
Chapter 1
Getting Started with
Android
Android is hot, and many people are developing Android applications (apps for
short). Perhaps you too would like to develop apps but are unsure about how to
get started. Although you could study Google’s online Android Developer’s
Guide (http://developer.android.com/index.html) to acquire the needed
knowledge, you might be overwhelmed by the guide’s vast amount of
information. In contrast, this chapter presents just enough theory to help you
grasp the basics. Following this theory are recipes that teach you how to
develop apps and prepare them for publication on Google Play
(https://play.google.com/store).
What Is Android?
The Android Developer’s Guide formerly defined Android as a software stack----
a set of software subsystems needed to deliver a fully functional solution---- for
mobile devices. This stack includes an operating system (a modified version of
the Linux kernel), middleware (software that connects the low-level operating
system to high-level apps) that’s partly based on Java, and key apps (written in
Java) such as a web browser (known as Browser) and a contact manager
(known as Contacts).
Android offers the following features:
Application framework enabling reuse and replacement of app
components (discussed later in this chapter)
www.it-ebooks.info
2 CHAPTER 1: Getting Started with Android
Bluetooth, EDGE, 3G, and WiFi support (hardware dependent)
Camera, GPS, compass, and accelerometer support
(hardware dependent)
Dalvik virtual machine optimized for mobile devices
GSM Telephony support (hardware dependent)
Integrated browser based on the open source WebKit engine
Media support for common audio, video, and still image
formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
Optimized graphics powered by a custom 2D graphics library;
3D graphics based on the OpenGL ES 1.0, 1.1, or 2.0
specification (hardware acceleration optional)
SQLite for structured data storage
Although not part of an Android device’s software stack, Android’s rich
development environment (including a device emulator and a plug-in for the
Eclipse integrated development environment [IDE]) could also be considered an
Android feature.
History of Android
Contrary to what you might expect, Android did not originate with Google.
Instead, Android was initially developed by Android, Inc., a small Palo Alto,
California-based startup company. Google bought this company in the summer
of 2005 and released a beta version of the Android SDK in November 2007.
On September 23, 2008, Google released Android 1.0, whose core features
included a web browser, camera support, Google Search, and more. Table 1-1
outlines subsequent releases. (Starting with version 1.5, each major release
comes under a code name that’s based on a dessert item.)
Table 1-1. Android Releases
Version Release Date and Changes
1.1 Google released SDK 1.1 on February 9, 2009. Changes included
showing/hiding the speakerphone dialpad and saving attachments in
messages.
1.5 (Cupcake)
Based on Linux
Kernel 2.6.27
Google released SDK 1.5 on April 30, 2009. Changes included
recording and watching videos in MPEG-4 and 3GP formats, populating
the home screen (a special app that is a starting point for using an
www.it-ebooks.info
CHAPTER 1: Getting Started with Android 3
Android device) with widgets (miniature app views), and animated
screen transitions.
1.6 (Donut)
Based on Linux
Kernel 2.6.29
Google released SDK 1.6 on September 15, 2009. Changes included an
expanded Gesture framework and the new GestureBuilder development
tool, an integrated camera/camcorder/gallery interface, support for
WVGA screen resolutions, and an updated search experience.
2.0/2.1 (Éclair)
Based on Linux
Kernel 2.6.29
Google released SDK 2.0 on October 26, 2009. Changes included live
wallpapers, numerous new camera features (including flash support,
digital zoom, scene mode, white balance, color effect, and macro
focus), improved typing speed on virtual keyboard, a smarter dictionary
that learns from word usage and includes contact names as
suggestions, improved Google Maps 3.1.2, and Bluetooth 2.1 support.
Google subsequently released SDK update 2.0.1 on December 3, 2009,
and SDK update 2.1 on January 12, 2010. Version 2.0.1 focused on
minor API changes, bug fixes, and framework behavioral changes.
Version 2.1 presented minor amendments to the API and bug fixes.
2.2 (Froyo)
Based on Linux
Kernel 2.6.32
Google released SDK 2.2 on May 20, 2009. Changes included the
integration of Chrome’s V8 JavaScript engine into the Browser app,
voice dialing and contact sharing over Bluetooth, Adobe Flash support,
additional app speed improvements through JIT compilation, and USB
tethering and WiFi hotspot functionality.
Google subsequently released SDK update 2.2.1 on January 18, 2011,
to offer bug fixes, security updates, and performance improvements. It
then released SDK update 2.2.2 on January 22, 2011, to provide minor
bug fixes, including SMS routing issues that affected the Nexus One.
Finally, Google released SDK update 2.2.3 on November 21, 2011, and
this contained two security patches.
2.3
(Gingerbread)
Based on Linux
Kernel 2.6.35
Google released SDK 2.3 on December 6, 2010. Changes included a
new concurrent garbage collector that improves an app’s
responsiveness, support for gyroscope and barometer sensing, support
for WebM/VP8 video playback and AAC audio encoding, support for
near field communication, and enhanced copy/paste functionality that
lets users select a word by press-hold, copy, and paste.
Google subsequently released SDK update 2.3.3 on February 9, 2011,
offering improvements and API fixes. SDK update 2.3.4 on April 28,
2011, added support for voice or video chat via Google Talk. SDK
update 2.3.5 on July 25, 2011, offered system enhancements, shadow
animations for list scrolling, improved battery efficiency, and more. SDK
update 2.3.6 on September 2, 2011, fixed a voice search bug. SDK
update 2.3.7 on September 21, 2011, brought support for Google
Wallet to the Nexus S 4G.
www.it-ebooks.info
4 CHAPTER 1: Getting Started with Android
3.0
(Honeycomb)
Based on Linux
2.6.36
Google released SDK 3.0 on February 22, 2011. Unlike previous
releases, version 3.0 focuses exclusively on tablets, such as Motorola
Xoom, the first tablet to be released (on February 24, 2011). In addition
to an improved user interface, version 3.0 improves multitasking,
supports multicore processors, supports hardware acceleration, and
provides a 3D desktop with redesigned widgets.
Google subsequently released SDK updates 3.1, 3.2, 3.2.1, 3.2.2, 3.2.4,
and 3.2.6 throughout 2011 and in February 2012.
4.0 (Ice Cream
Sandwich)
Based on Linux
Kernel 3.0.1
Google released SDK 4.0.1 on October 19, 2011. SDK 4.0.1 and 4.x
successors unify the 2.3.x smartphone and 3.x tablet SDKs. Features
include 1080p video recording and a customizable launcher.
Google subsequently released SDK updates 4.0.2, 4.0.3, and 4.0.4 in
late 2011 and in March 2012.
4.1 (Jelly Bean) Google released SDK 4.1 on June 27, 2012. Features include vsync
timing, triple buffering, automatically resizable app widgets, improved
voice search, multichannel audio, and expandable notifications. An
over-the-air update (version 4.1.1) was released later in July.
In early October, Google released SDK 4.1.2, which offers lock/home
screen rotation support for the Nexus 7, one-finger gestures to
expand/collapse notifications, and bug fixes/performance
enhancements. Then, in late October, Google released SDK 4.2, which
offers Photo Sphere panorama photos, multiple user accounts (tablets
only), a “Daydream” screensaver that activates when the device is idle
or docked, notification power controls, support for a wireless display
(Miracast), and more.
Android Architecture
The Android software stack consists of apps at the top, middleware (consisting
of an application framework, libraries, and the Android runtime) in the middle,
and a Linux kernel with various drivers at the bottom. Figure 1-1 shows this
layered architecture.
www.it-ebooks.info
CHAPTER 1: Getting Started with Android 5
Figure 1-1. Android’s layered architecture consists of several major parts.
Users care about apps, and Android ships with a variety of useful core apps,
which include Browser, Contacts, and Phone. All apps are written in the Java
programming language. Apps form the top layer of Android’s architecture.
NOTE: Apps are written in a nonstandard Java implementation that combines
Android-specific APIs with Java 5 APIs and a small amount of Java 6 (such as the
java.io.File class’s boolean setExecutable(boolean executable,
boolean ownerOnly) method). Because Android does not support most Java 6
and all Java 7 APIs, you cannot leverage newer Java APIs and dependent features.
For example, you cannot use Java 7’s try-with-resources statement, which depends
upon Java 7’s java.lang.AutoCloseable interface.
www.it-ebooks.info
6 CHAPTER 1: Getting Started with Android
Each Android version (including updates) is assigned an API level, an integer value
uniquely identifying the framework API revision offered by that version of the Android
platform. For example, Android 4.1 is assigned API Level 16 and Android 2.3.4 is
assigned API Level 10. APIs with higher API levels typically cannot be used on devices
with lower API levels. (Google’s support library, which is discussed in Chapter 7,
makes certain newer APIs available to older platform versions.) For example, you
typically cannot use an API at Level 16 on a device that supports only API Level 10
(and lower). API-level constants are available in the
android.os.Build.VERSION_CODES class. Consult “Android API Levels”
(http://developer.android.com/guide/topics/manifest/uses-sdkelement.html#ApiLevels) in the Android Developer’s Guide to learn more about
API levels.
Directly beneath the app layer is the application framework, a set of high-level
building blocks for creating apps. The application framework is preinstalled on
Android devices and consists of the following components:
Activity Manager: This component provides an app’s life cycle
and maintains a shared activity stack for navigating within and
among apps. Both topics are discussed later in this chapter.
Content Providers: These components encapsulate data (such
as the Browser app’s bookmarks) that can be shared among
apps.
Location Manager: This component makes it possible for an
Android device to be aware of its physical location.
Notification Manager: This component lets an app notify the
user of a significant event (such as a message’s arrival)
without interrupting what the user is currently doing.
Package Manager: This component lets an app learn about
other app packages that are currently installed on the device.
(App packages are discussed later in this chapter.)
Resource Manager: This component lets an app access its
resources, a topic that’s discussed later in this chapter.
Telephony Manager: This component lets an app learn about a
device’s telephony services. It also handles making and
receiving phone calls.
www.it-ebooks.info
CHAPTER 1: Getting Started with Android 7
View System: This component manages user interface
elements and user interface-oriented event generation. (These
topics are briefly discussed later in this chapter.)
Window Manager: This component organizes the screen’s real
estate into windows, allocates drawing surfaces, and performs
other window-related jobs.
The components of the application framework rely on a set of C/C++ libraries to
perform their functions. Developers interact with the following libraries by way of
framework APIs:
FreeType: This library supports bitmap and vector font
rendering.
libc: This library is a BSD-derived implementation of the
standard C system library, tuned for embedded Linux-based
devices.
LibWebCore: This library offers a modern and fast web
browser engine that powers the Android browser and an
embeddable web view. It’s based on WebKit
(http://en.wikipedia.org/wiki/WebKit) and is also used by
the Google Chrome and Apple Safari browsers.
Media Framework: These libraries, which are based on
PacketVideo’s OpenCORE, support the playback and
recording of many popular audio and video formats, as well as
working with static image files. Supported formats include
MPEG4, H.264, MP3, AAC, AMR, JPEG, and PNG.
OpenGL | ES: These 3D graphics libraries provide an OpenGL
implementation based on OpenGL ES 1.0/1.1/2.0 APIs. They
use hardware 3D acceleration (where available) or the included
(and highly optimized) 3D software rasterizer.
SGL: This library provides the underlying 2D graphics engine.
SQLite: This library provides a powerful and lightweight
relational database engine that’s available to all apps and
that’s also used by Mozilla Firefox and Apple’s iPhone for
persistent storage.
SSL: This library provides secure sockets layer‒based security
for network communication.
www.it-ebooks.info
8 CHAPTER 1: Getting Started with Android
Surface Manager: This library manages access to the display
subsystem, and it seamlessly composites 2D and 3D graphic
layers from multiple apps.
Android provides a runtime environment that consists of core libraries
(implementing a subset of the Apache Harmony Java version 5 implementation)
and the Dalvik virtual machine (a non-Java virtual machine that’s based on
processor registers instead of being stack-based).
NOTE: Google’s Dan Bornstein created Dalvik and named this virtual machine after an
Icelandic fishing village where some of his ancestors lived.
Each Android app defaults to running in its own Linux process, which hosts an
instance of Dalvik. This virtual machine has been designed so that devices can
run multiple virtual machines efficiently. This efficiency is largely due to Dalvik
executing Dalvik Executable (DEX)-based files. DEX is a format that’s optimized
for a minimal memory footprint.
NOTE: Android starts a process when any part of the app needs to execute, and it
shuts down the process when it’s no longer needed and system resources are
required by other apps.
Perhaps you’re wondering how it’s possible to have a non-Java virtual machine
run Java code. The answer is that Dalvik doesn’t run Java code. Instead,
Android transforms compiled Java classfiles into the DEX format via its dx tool,
and it’s this resulting code that gets executed by Dalvik.
Finally, the libraries and Android runtime rely on the Linux kernel (version 2.6.x
or 3.0.x) for underlying core services, such as threading, low-level memory
management, a network stack, process management, and a driver model.
Furthermore, the kernel acts as an abstraction layer between the hardware and
the rest of the software stack.
ANDROID SECURITY MODEL
Android’s architecture includes a security model that prevents apps from performing operations
considered harmful to other apps, Linux, or users. This security model, which is mostly based on
process level enforcement via standard Linux features (such as user and group IDs), places
processes in a security sandbox.
www.it-ebooks.info
CHAPTER 1: Getting Started with Android 9
By default, the sandbox prevents apps from reading or writing the user’s private data (such as
contacts or e-mails), reading or writing another app’s files, performing network access, keeping
the device awake, accessing the camera, and so on. Apps that need to access the network or
perform other sensitive operations must first obtain permission to do so.
Android handles permission requests in various ways, typically by automatically allowing or
disallowing the request based upon a certificate or by prompting the user to grant or revoke the
permission. Permissions required by an app are declared in the app’s manifest file (discussed
later in this chapter) so that they are known to Android when the app is installed. These
permissions won’t subsequently change.
App Architecture
Android app architecture differs from desktop application architecture. App
architecture is largely based upon components that communicate via intents,
resources that are often used in user interface contexts, a manifest that
describes the app’s components (and more), and an app package that stores
components, resources, and the manifest.
Components
An app consists of components (activities, services, broadcast receivers, and
content providers) that run in a Linux process and that are managed by Android:
Activities present user interface screens.
Services perform lengthy jobs (such as playing music) in the
background and don’t provide user interfaces.
Broadcast receivers receive and react to broadcasts from
Android or other components.
Content providers encapsulate data and make them available
to apps.
Each component is implemented as a class that’s stored in the same Java
package, which is known as the app package. From the Android SDK
perspective, each class’s source file is stored under a package directory
hierarchy that is situated underneath an src directory. (You will learn about the
Android SDK later in this chapter.)
Not all of these components need to be present in an app. For example, one
app might consist of activities only, whereas another app might consist of
activities and a service.
www.it-ebooks.info
10 CHAPTER 1: Getting Started with Android
NOTE: An app’s activities, services, broadcast receivers, and/or content providers
share a set of system resources, such as databases, preferences, a filesystem, and
the Linux process.
Android communicates with activities, services, and broadcast receivers via
intents, which are messages that describe operations to perform (such as
launch an activity) or (in the case of broadcasts) that provide descriptions of
external events that have occurred (a device’s camera being activated, for
example) and are being announced. Activities, services, and broadcast receivers
can also use intents to communicate among themselves.
Intents are implemented as instances of the android.content.Intent class. An
Intent object describes a message in terms of some combination of the
following items:
Action: A string naming the action to be performed or, in the
case of broadcast intents, the action that took place and is
being reported. Actions are described by Intent constants
such as ACTION_CALL (initiate a phone call), ACTION_EDIT
(display data for the user to edit), and ACTION_MAIN (start up as
the initial activity). You can also define your own action strings
for activating the components in your app. These strings
should include the app package as a prefix
("com.example.project.GET_NEWSFEEDS", for example).
Category: A string that provides additional information about
the kind of component that should handle the intent. For
example, CATEGORY_LAUNCHER means that the calling activity
should appear in the device’s app launcher as a top-level app.
(The app launcher is briefly discussed in Recipe 1-4.)
Component name: A string that specifies the fully qualified
name (package plus name) of a component class to use for
the intent. The component name is optional. If set, the Intent
object is delivered to an instance of the designated class. If
not set, Android uses other information in the Intent object to
locate a suitable target.
Data: The uniform resource identifier of the data on which to
operate (such as a person record in a contacts database).
www.it-ebooks.info
CHAPTER 1: Getting Started with Android 11
Extras: A set of key-value pairs providing additional
information that should be delivered to the component
handling the intent. For example, given an action for sending
an e-mail message, this information could include the
message’s subject, body, and so on.
Flags: Bit values that instruct Android on how to launch an
activity (for example, which task the activity should belong
to----tasks are discussed later in this chapter) and how to treat
the activity after launch (for example, whether the activity can
be considered a recent activity). Flags are represented by
constants in the Intent class; for example,
FLAG_ACTIVITY_NEW_TASK specifies that this activity will
become the start of a new task on this activity stack----the
activity stack is discussed later in this chapter.
Type: The MIME type of the intent data. Normally, Android
infers a type from the data. By specifying a type, you disable
that inference.
Intents can be classified as explicit or implicit. An explicit intent designates the
target component by its name (the previously mentioned component name item
is assigned a value). Because component names are usually unknown to the
developers of other apps, explicit intents are typically used for app-internal
messages (such as an activity that launches another activity located within the
same app). Android delivers an explicit intent to an instance of the designated
target class. Only the Intent object’s component name matters for determining
which component should get the intent.
An implicit intent doesn’t name a target (the component name is not assigned a
value). Implicit intents are often used to start components in other apps. Android
searches for the best component (a single activity or service to perform the
requested action) or components (a set of broadcast receivers to respond to the
broadcast announcement) to handle the implicit intent. During the search,
Android compares the contents of the Intent object to intent filters, manifest
information associated with components that can potentially receive intents.
Filters advertise a component’s capabilities and identify only those intents that
the component can handle. They open up the component to the possibility of
receiving implicit intents of the advertised type. If a component has no intent
filters, it can receive only explicit intents. In contrast, a component with filters
can receive explicit and implicit intents. Android consults an Intent object’s
action, category, data, and type when comparing the intent against an intent
filter. It doesn’t take extras and flags into consideration.
www.it-ebooks.info
12 CHAPTER 1: Getting Started with Android
NOTE: Android widely uses intents, which offers many opportunities to replace
existing components with your own components. For example, Android provides the
intent for sending an e-mail. Your app can send this intent to activate the standard
mail app, or it can register an activity that responds to the intent, replacing the
standard mail app with its own activity.
This component-oriented architecture lets an app reuse the components of
other apps, provided that those other apps permit reuse of their components.
Component reuse reduces the overall memory footprint, which is very important
for devices with limited memory.
For example, you’re creating a drawing app that lets users choose a color from
a palette, and another app contains a suitable color chooser and permits this
component to be reused. In this scenario, the drawing app can call upon that
other app’s color chooser to have the user select a color rather than provide its
own color chooser. The drawing app doesn’t contain the other app’s color
chooser or even link to this other app. Instead, it starts up the other app’s color
chooser component when needed.
NOTE: Android starts a process when any part of the app (such as the
aforementioned color chooser) is needed, and it instantiates the Java objects for that
part. This is why Android’s apps don’t have a single entry point (no C-style main()
function, for example). Instead, apps use components that are instantiated and run as
needed.
Activities in Depth
An activity is a component that presents a user interface screen with which the
user interacts. For example, Android’s Contacts app includes an activity for
entering a new contact, its Phone app includes an activity for dialing a phone
number, and its Calculator app includes an activity for performing basic
calculations (see Figure 1-2).
www.it-ebooks.info