Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 953 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
953
Dung lượng
10,23 MB
Nội dung
COMPANION eBOOK
US $44.99
Shelve in
Mobile Computing
User level:
Intermediate
www.apress.com
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
A
ndroid Recipes teaches you how to develop top-notch apps using a proven
problem-solution approach. First, a problem is identified. Then a clear expla-
nation 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 edi-
tion of AndroidRecipes 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
1
Chapter
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 s e t o f s oft wa re s u bs ys te ms n e ed e d to d e li ve r a f u ll y f unc ti on a l s ol ut io n 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
CHAPTER 1: Getting Started with Android
2
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
CHAPTER 1: Getting Started with Android
4
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
CHAPTER 1: Getting Started with Android
6
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-sdk-
element.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
[...]... 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 11 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... 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 Extras: A set of key-value pairs providing additional Flags: Bit values that instruct Android on how to launch an... 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. .. 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 CHAPTER 1: Getting Started with Android Figure 1-2 The main activity of Android s Calculator app lets the user perform... override various Activity life cycle callback methods that Android calls during the life of an activity For example, the SimpleActivity class in Listing 1-1 extends Activity and also overrides the void onCreate(Bundle bundle) and void onDestroy() life cycle callback methods Listing 1-1 A Skeletal Activity import android. app.Activity; import android. os.Bundle; public class SimpleActivity extends Activity... passed an android. os.Bundle object containing the activity’s previous state, if that state was captured (via void onSaveInstanceState(Bundle outState)); otherwise, the null reference is passed Android always calls the onStart() method after calling onCreate(Bundle) All meaningful activities override onCreate(Bundle) onStart() is called just before the activity becomes visible to the user Android calls... started again Android always calls onStart() after calling onRestart() onResume() is called just before the activity starts interacting with the user At this point the activity has the focus and user input is directed to the activity Android always calls the onPause() method after calling onResume(), but only when the activity must be paused www.it-ebooks.info CHAPTER 1: Getting Started with Android ... view groups) NOTE: Android refers to views as widgets Don’t confuse widget in this context with the widgets that are shown on the Android home screen Although the same term is used, user interface widgets and home screen widgets are different User interface widgets are components; home screen widgets are miniature views of running apps Views are described by subclasses of the concrete android. view.View... android. view.View class and are analogous to Java Swing components The android. widget package contains various View subclasses, such as Button, EditText, and TextView (the parent of EditText) View groups are described by subclasses of the abstract android. view.ViewGroup class (which subclasses View) and are analogous to Java Swing containers The android. widget package contains various subclasses, such as LinearLayout... activity that initiated the music leaves the screen Services are described by subclasses of the abstract android. app.Service class, which is an indirect subclass of Context www.it-ebooks.info CHAPTER 1: Getting Started with Android Service subclasses override various Service life cycle callback methods that Android calls during the life of a service For example, the SimpleService class in Listing 1-2 extends . 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. command-line/
Android SDK and Eclipse /Android SDK environments
Crammed with insightful instruction and helpful examples, this second edi-
tion of Android Recipes