Tải bản đầy đủ (.pdf) (868 trang)

718 professional android 4 application development

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (26.62 MB, 868 trang )

www.it-ebooks.info


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd ii

4/11/2012 10:37:19 AM


Meier02275 ffirs V2 - 03/22/2012

PROFESSIONAL
ANDROID™ 4 APPLICATION DEVELOPMENT
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxvii
CHAPTER 1

Hello, Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

CHAPTER 2

Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19

CHAPTER 3

Creating Applications and Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

CHAPTER 4


Building User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

CHAPTER 5

Intents and Broadcast Receivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

CHAPTER 6

Using Internet Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

CHAPTER 7

Files, Saving State, and Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

CHAPTER 8

Databases and Content Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

CHAPTER 9

Working in the Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331

CHAPTER 10

Expanding the User Experience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

CHAPTER 11

Advanced User Experience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425


CHAPTER 12

Hardware Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481

CHAPTER 13

Maps, Geocoding, and Location-Based Services . . . . . . . . . . . . . . . . . 513

CHAPTER 14

Invading the Home Screen. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565

CHAPTER 15

Audio, Video, and Using the Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621

CHAPTER 16

Bluetooth, NFC, Networks, and Wi-Fi. . . . . . . . . . . . . . . . . . . . . . . . . . . . 665

CHAPTER 17

Telephony and SMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701

CHAPTER 18

Advanced Android Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739

CHAPTER 19


Monetizing, Promoting, and Distributing Applications . . . . . . . . . . . . . .771

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787

www.it-ebooks.info

ffirs.indd i

4/11/2012 10:37:18 AM


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd ii

4/11/2012 10:37:19 AM


12

Meier02275 ffirs V2 - 03/22/2012

PROFESSIONAL

Android™ 4 Application Development

www.it-ebooks.info


ffirs.indd iii

4/11/2012 10:37:19 AM


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd iv

4/11/2012 10:37:19 AM


Meier02275 ffirs V2 - 03/22/2012

PROFESSIONAL

Android™ 4 Application Development

Reto Meier

www.it-ebooks.info

ffirs.indd v

4/11/2012 10:37:19 AM


Book Title <Chapter No> V2 - MM/DD/2010


Professional Android™ 4 Application Development

Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256

www.wiley.com
Copyright © 2012 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-10227-5
ISBN: 978-1-118-22385-7 (ebk)
ISBN: 978-1-118-23722-9 (ebk)
ISBN: 978-1-118-26215-3 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the
1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978)
750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department,
John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://
www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect
to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without
limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional
materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the
understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional
assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author
shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation
and/or a potential source of further information does not mean that the author or the publisher endorses the information the

organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web
sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United
States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard
print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD
or DVD that is not included in the version you purchased, you may download this material at http://booksupport
.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2011945019
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress
are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other
countries, and may not be used without written permission. Android is a trademark of Google, Inc. All other trademarks
are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned
in this book.

www.it-ebooks.info

ffirs.indd vi

4/11/2012 10:37:21 AM


10

Meier02275 ffirs V2 - 03/22/2012

To Kris

www.it-ebooks.info


ffirs.indd vii

4/11/2012 10:37:21 AM


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd viii

4/11/2012 10:37:21 AM


12

Meier02275 ffirs V2 - 03/22/2012

ABOUT THE AUTHOR

RETO MEIER grew up in Perth, Western Australia, and then lived in London for 6 years before
moving to the San Francisco Bay Area in 2011.

Reto currently works as a Developer Advocate on the Android team at Google, helping Android
developers create the best applications possible. Reto is an experienced software developer with
more than 10 years of experience in GUI application development. Before coming to Google, he
worked in various industries, including offshore oil and gas and fi nance.
Always interested in emerging technologies, Reto has been involved in Android since the initial
release in 2007.
You can fi nd out entirely too much about Reto’s interests and hobbies on his web site, The

Radioactive Yak (), or on Google+ (http://profiles
.google.com/reto.meier) or Twitter (www.twitter.com/retomeier), where he shares more than
he probably should.

www.it-ebooks.info

ffirs.indd ix

4/11/2012 10:37:21 AM


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd x

4/11/2012 10:37:22 AM


12

Meier02275 ffirs V2 - 03/22/2012

ABOUT THE TECHNICAL EDITOR

DAN ULERY is a software engineer with experience in .NET, Java, and PHP development, as well as

in deployment engineering. He graduated from the University of Idaho with a Bachelor of Science
degree in computer science and a minor in mathematics.


www.it-ebooks.info

ffirs.indd xi

4/11/2012 10:37:22 AM


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd xii

4/11/2012 10:37:22 AM


12

Book Title <Chapter No> V2 - MM/DD/2010

CREDITS

EXECUTIVE EDITOR

PRODUCTION MANAGER

Robert Elliott

Tim Tate


PROJECT EDITOR

VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER

John Sleeva

Richard Swadley
TECHNICAL EDITOR

Dan Ulery

VICE PRESIDENT AND EXECUTIVE PUBLISHER

Neil Edde
PRODUCTION EDITOR

Kathleen Wisor

ASSOCIATE PUBLISHER

Jim Minatel
COPY EDITOR

San Dee Phillips

PROJECT COORDINATOR, COVER

Katie Crocker

EDITORIAL MANAGER

Mary Beth Wakefield

PROOFREADER

Jen Larsen, Word One New York
FREELANCER EDITORIAL MANAGER

Rosemarie Graham

INDEXER

Johnna VanHoose Dinse
ASSOCIATE DIRECTOR OF MARKETING

David Mayhew

COVER DESIGNER

Ryan Sneed
MARKETING MANAGER

Ashley Zurcher

COVER IMAGE

© Linda Bucklin / iStockPhoto
BUSINESS MANAGER


Amy Knies

www.it-ebooks.info

ffirs.indd xiii

4/11/2012 10:37:22 AM


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd xiv

4/11/2012 10:37:22 AM


12

Meier02275 ffirs V2 - 03/22/2012

ACKNOWLEDGMENTS

FIRST, I’D LIKE TO THANK KRISTY, whose love, patience, and understanding are pushed to new limits
every time I forget what’s involved in writing a book and agree to do another one. Your support
makes everything I do possible.

A big thank you to my friends and colleagues at Google, particularly the Android engineers and my
colleagues in developer relations. The pace at which Android grows makes life difficult for those of

us who choose to write books, but the opportunities it creates for developers makes the stress and
rewrites easy to bear.
I also thank Dan Ulery for his sharp eye and valuable insights; Robert Elliot and John Sleeva for
their patience in waiting for me to get this book fi nished; San Dee Phillips; and the whole team at
Wrox for helping to get it done.
A special shout-out goes out to the entire Android developer community. Your passion, hard work,
and excellent applications have helped make Android the huge success that it is. Thank you.

www.it-ebooks.info

ffirs.indd xv

4/11/2012 10:37:22 AM


Meier02275 ffirs V2 - 03/22/2012

www.it-ebooks.info

ffirs.indd xvi

4/11/2012 10:37:22 AM


Meier02275 ftoc V2 - 03/22/2012

CONTENTS

INTRODUCTION


xxxvii

CHAPTER 1: HELLO, ANDROID

A Little Background

1

2

The Not-So-Distant Past
Living in the Future

2
3

What Android Isn’t
Android: An Open Platform for Mobile Development
Native Android Applications
Android SDK Features
Access to Hardware, Including Camera, GPS, and Sensors
Data Transfers Using Wi-Fi, Bluetooth, and NFC
Maps, Geocoding, and Location-Based Services
Background Services
SQLite Database for Data Storage and Retrieval
Shared Data and Inter-Application Communication
Using Widgets and Live Wallpaper to Enhance the Home Screen
Extensive Media Support and 2D/3D Graphics
Cloud to Device Messaging
Optimized Memory and Process Management


Introducing the Open Handset Alliance
What Does Android Run On?
Why Develop for Mobile?
Why Develop for Android?
Factors Driving Android’s Adoption
What Android Has That Other Platforms Don’t Have
The Changing Mobile Development Landscape

3
4
5
6
6
7
7
7
8
8
9
9
9
10

10
10
11
11
12
12

13

Introducing the Development Framework

14

What Comes in the Box
Understanding the Android Software Stack
The Dalvik Virtual Machine
Android Application Architecture
Android Libraries

14
15
16
17
18

www.it-ebooks.info

ftoc.indd xvii

4/11/2012 10:34:48 AM


Meier02275 ftoc V2 - 03/22/2012

CONTENTS

CHAPTER 2: GETTING STARTED


Developing for Android

19

20

What You Need to Begin
Downloading and Installing the Android SDK
Downloading and Installing Updates to the SDK
Developing with Eclipse
Using the Android Developer Tools Plug-In for Eclipse
Using the Support Package
Creating Your First Android Application
Creating a New Android Project
Creating an Android Virtual Device
Creating Launch Configurations
Running and Debugging Your Android Application
Understanding Hello World
Types of Android Applications
Foreground Applications
Background Applications
Intermittent Applications
Widgets and Live Wallpapers

Developing for Mobile and Embedded Devices
Hardware-Imposed Design Considerations
Be Efficient
Expect Limited Capacity
Design for Different Screens

Expect Low Speeds, High Latency
At What Cost?
Considering the User’s Environment
Developing for Android
Being Fast and Efficient
Being Responsive
Ensuring Data Freshness
Developing Secure Applications
Ensuring a Seamless User Experience
Providing Accessibility

Android Development Tools
The Android Virtual Device Manager
Android SDK Manager
The Android Emulator

20
21
23
23
24
27
28
28
30
30
33
33
36
36

37
37
37

38
38
38
39
39
40
41
42
43
43
44
45
45
46
47

47
48
49
50

xviii

www.it-ebooks.info

ftoc.indd xviii


4/11/2012 10:34:49 AM


Meier02275 ftoc V2 - 03/22/2012

CONTENTS

The Dalvik Debug Monitor Service
The Android Debug Bridge
The Hierarchy Viewer and Lint Tool
Monkey and Monkey Runner

CHAPTER 3: CREATING APPLICATIONS AND ACTIVITIES

What Makes an Android Application?
Introducing the Application Manifest File
A Closer Look at the Application Manifest

Using the Manifest Editor
Externalizing Resources

50
51
51
52

53

54

55
56

63
64

Creating Resources
Simple Values
Styles and Themes
Drawables
Layouts
Animations
Menus
Using Resources
Using Resources in Code
Referencing Resources Within Resources
Using System Resources
Referring to Styles in the Current Theme
Creating Resources for Different Languages and Hardware
Runtime Configuration Changes

The Android Application Lifecycle
Understanding an Application’s Priority and Its Process’ States
Introducing the Android Application Class
Extending and Using the Application Class
Overriding the Application Lifecycle Events

A Closer Look at Android Activities
Creating Activities
The Activity Lifecycle

Activity Stacks
Activity States
Monitoring State Changes
Understanding Activity Lifetimes
Android Activity Classes

65
65
68
68
69
70
73
74
74
75
76
76
77
79

81
82
83
83
84

86
86
87

88
88
89
91
93

xix

www.it-ebooks.info

ftoc.indd xix

4/11/2012 10:34:49 AM


Meier02275 ftoc V2 - 03/22/2012

CONTENTS

CHAPTER 4: BUILDING USER INTERFACES

95

Fundamental Android UI Design
Android User Interface Fundamentals

96
97

Assigning User Interfaces to Activities


Introducing Layouts

97

98

Defining Layouts
Using Layouts to Create Device Independent User Interfaces
Using a Linear Layout
Using a Relative Layout
Using a Grid Layout
Optimizing Layouts
Redundant Layout Containers Are Redundant
Avoid Using Excessive Views
Using Lint to Analyze Your Layouts

To-Do List Example
Introducing Fragments

99
100
100
101
102
103
103
105
106


107
114

Creating New Fragments
The Fragment Lifecycle
Fragment-Specific Lifecycle Events
Fragment States
Introducing the Fragment Manager
Adding Fragments to Activities
Using Fragment Transactions
Adding, Removing, and Replacing Fragments
Using the Fragment Manager to Find Fragments
Populating Dynamic Activity Layouts with Fragments
Fragments and the Back Stack
Animating Fragment Transactions
Interfacing Between Fragments and Activities
Fragments Without User Interfaces
Android Fragment Classes
Using Fragments for Your To-Do List

The Android Widget Toolbox
Creating New Views
Modifying Existing Views
Customizing Your To-Do List
Creating Compound Controls
Creating Simple Compound Controls Using Layouts
Creating Custom Views
Creating a New Visual Interface
Handling User Interaction Events


115
116
119
119
120
120
121
122
122
123
124
125
126
126
128
128

132
133
133
135
138
141
141
142
147

xx

www.it-ebooks.info


ftoc.indd xx

4/11/2012 10:34:49 AM


Meier02275 ftoc V2 - 03/22/2012

CONTENTS

Supporting Accessibility in Custom Views
Creating a Compass View Example
Using Custom Controls

Introducing Adapters

148
149
155

156

Introducing Some Native Adapters
Customizing the Array Adapter
Using Adapters to Bind Data to a View
Customizing the To-Do List Array Adapter
Using the Simple Cursor Adapter

CHAPTER 5: INTENTS AND BROADCAST RECEIVERS


Introducing Intents

156
156
158
158
162

165

166

Using Intents to Launch Activities
Explicitly Starting New Activities
Implicit Intents and Late Runtime Binding
Determining If an Intent Will Resolve
Returning Results from Activities
Native Android Actions
Introducing Linkify
Native Linkify Link Types
Creating Custom Link Strings
Using the Match Filter
Using the Transform Filter
Using Intents to Broadcast Events
Broadcasting Events with Intents
Listening for Broadcasts with Broadcast Receivers
Broadcasting Ordered Intents
Broadcasting Sticky Intents
Introducing the Local Broadcast Manager
Introducing Pending Intents


Creating Intent Filters and Broadcast Receivers
Using Intent Filters to Service Implicit Intents
How Android Resolves Intent Filters
Finding and Using Intents Received Within an Activity
Passing on Responsibility
Selecting a Contact Example
Using Intent Filters for Plug-Ins and Extensibility
Supplying Anonymous Actions to Applications
Discovering New Actions from Third-Party Intent Receivers
Incorporating Anonymous Actions as Menu Items
Listening for Native Broadcast Intents

166
167
167
168
169
172
174
174
175
176
176
177
177
178
180
181
182

182

183
183
185
186
187
187
193
193
194
195
196
xxi

www.it-ebooks.info

ftoc.indd xxi

4/11/2012 10:34:49 AM


Meier02275 ftoc V2 - 03/22/2012

CONTENTS

Monitoring Device State Changes Using Broadcast Intents
Listening for Battery Changes
Listening for Connectivity Changes
Listening for Docking Changes

Managing Manifest Receivers at Run Time

CHAPTER 6: USING INTERNET RESOURCES

Downloading and Parsing Internet Resources
Connecting to an Internet Resource
Parsing XML Using the XML Pull Parser
Creating an Earthquake Viewer

Using the Download Manager
Downloading Files
Customizing Download Manager Notifications
Specifying a Download Location
Cancelling and Removing Downloads
Querying the Download Manager

197
197
198
199
199

201

201
202
203
205

210

211
213
213
214
215

Using Internet Services
Connecting to Google App Engine
Best Practices for Downloading Data Without Draining
the Battery

217
218

CHAPTER 7: FILES, SAVING STATE, AND PREFERENCES

221

Saving Simple Application Data
Creating and Saving Shared Preferences
Retrieving Shared Preferences
Creating a Settings Activity for the Earthquake Viewer
Introducing the Preference Framework and the
Preference Activity

222
222
223
223


Defining a Preference Screen Layout in XML
Native Preference Controls
Using Intents to Import System Preferences into Preference Screens
Introducing the Preference Fragment
Defining the Preference Fragment Hierarchy
Using Preference Headers
Introducing the Preference Activity
Backward Compatibility and Preference Screens
Finding and Using the Shared Preferences Set by Preference Screens
Introducing On Shared Preference Change Listeners

219

231
232
234
234
235
235
236
237
238
238

xxii

www.it-ebooks.info

ftoc.indd xxii


4/11/2012 10:34:49 AM


Meier02275 ftoc V2 - 03/22/2012

CONTENTS

Creating a Standard Preference Activity for the Earthquake Viewer
Persisting the Application Instance State
Saving Activity State Using Shared Preferences
Saving and Restoring Activity Instance State
Using the Lifecycle Handlers
Saving and Restoring Fragment Instance State
Using the Lifecycle Handlers

Including Static Files as Resources
Working with the File System
File-Management Tools
Using Application-Specific Folders to Store Files
Creating Private Application Files
Using the Application File Cache
Storing Publicly Readable Files

CHAPTER 8: DATABASES AND CONTENT PROVIDERS

Introducing Android Databases
SQLite Databases
Content Providers

238

242
242
242
243

245
246
246
246
247
248
248

251

252
252
252

Introducing SQLite
Content Values and Cursors
Working with SQLite Databases
Introducing the SQLiteOpenHelper
Opening and Creating Databases Without the SQLite Open Helper
Android Database Design Considerations
Querying a Database
Extracting Values from a Cursor
Adding, Updating, and Removing Rows
Inserting Rows
Updating Rows

Deleting Rows

Creating Content Providers

253
253
254
255
257
257
257
259
260
260
261
261

262

Registering Content Providers
Publishing Your Content Provider’s URI Address
Creating the Content Provider’s Database
Implementing Content Provider Queries
Content Provider Transactions
Storing Files in a Content Provider
A Skeleton Content Provider Implementation

262
263
264

264
266
268
270

xxiii

www.it-ebooks.info

ftoc.indd xxiii

4/11/2012 10:34:49 AM


×