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

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 (24.84 MB, 868 trang )

Meier02275  rs V2 - 03/22/2012
ffirs.indd iiffirs.indd ii 4/11/2012 10:37:19 AM4/11/2012 10:37:19 AM
Downloa d f r o m W o w ! e B o o k < w w w.woweb o o k . c o m >
Meier02275  rs 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
ffirs.indd iffirs.indd i 4/11/2012 10:37:18 AM4/11/2012 10:37:18 AM
Meier02275  rs V2 - 03/22/2012
ffirs.indd iiffirs.indd ii 4/11/2012 10:37:19 AM4/11/2012 10:37:19 AM


12 Meier02275  rs V2 - 03/22/2012
PROFESSIONAL
Android

4 Application Development
ffirs.indd iiiffirs.indd iii 4/11/2012 10:37:19 AM4/11/2012 10:37:19 AM
Meier02275  rs V2 - 03/22/2012
ffirs.indd ivffirs.indd iv 4/11/2012 10:37:19 AM4/11/2012 10:37:19 AM
Meier02275  rs V2 - 03/22/2012
PROFESSIONAL
Android

4 Application Development
Reto Meier
ffirs.indd vffirs.indd v 4/11/2012 10:37:19 AM4/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, elec-
tronic, 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 pay-
ment 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 specifi cally disclaim all warranties, including without
limitation warranties of fi tness 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.
ffirs.indd viffirs.indd vi 4/11/2012 10:37:21 AM4/11/2012 10:37:21 AM
10 Meier02275  rs V2 - 03/22/2012
To Kris
ffirs.indd viiffirs.indd vii 4/11/2012 10:37:21 AM4/11/2012 10:37:21 AM
Meier02275  rs V2 - 03/22/2012
ffirs.indd viiiffirs.indd viii 4/11/2012 10:37:21 AM4/11/2012 10:37:21 AM
12 Meier02275  rs 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.
ffirs.indd ixffirs.indd ix 4/11/2012 10:37:21 AM4/11/2012 10:37:21 AM
Meier02275  rs V2 - 03/22/2012
ffirs.indd xffirs.indd x 4/11/2012 10:37:22 AM4/11/2012 10:37:22 AM
12 Meier02275  rs 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.
ffirs.indd xiffirs.indd xi 4/11/2012 10:37:22 AM4/11/2012 10:37:22 AM
Meier02275  rs V2 - 03/22/2012
ffirs.indd xiiffirs.indd xii 4/11/2012 10:37:22 AM4/11/2012 10:37:22 AM
12 Book Title <Chapter No> V2 - MM/DD/2010
CREDITS
EXECUTIVE EDITOR
Robert Elliott
PROJECT EDITOR
John Sleeva
TECHNICAL EDITOR
Dan Ulery
PRODUCTION EDITOR
Kathleen Wisor
COPY EDITOR
San Dee Phillips
EDITORIAL MANAGER
Mary Beth Wakefi eld
FREELANCER EDITORIAL MANAGER
Rosemarie Graham
ASSOCIATE DIRECTOR OF MARKETING
David Mayhew
MARKETING MANAGER
Ashley Zurcher
BUSINESS MANAGER
Amy Knies
PRODUCTION MANAGER
Tim Tate
VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER

Richard Swadley
VICE PRESIDENT AND EXECUTIVE PUBLISHER
Neil Edde
ASSOCIATE PUBLISHER
Jim Minatel
PROJECT COORDINATOR, COVER
Katie Crocker
PROOFREADER
Jen Larsen, Word One New York
INDEXER
Johnna VanHoose Dinse
COVER DESIGNER
Ryan Sneed
COVER IMAGE
© Linda Bucklin / iStockPhoto
ffirs.indd xiiiffirs.indd xiii 4/11/2012 10:37:22 AM4/11/2012 10:37:22 AM
Meier02275  rs V2 - 03/22/2012
ffirs.indd xivffirs.indd xiv 4/11/2012 10:37:22 AM4/11/2012 10:37:22 AM
12 Meier02275  rs 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 diffi cult 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.
ffirs.indd xvffirs.indd xv 4/11/2012 10:37:22 AM4/11/2012 10:37:22 AM
Meier02275  rs V2 - 03/22/2012
ffirs.indd xviffirs.indd xvi 4/11/2012 10:37:22 AM4/11/2012 10:37:22 AM
Downloa d f r o m W o w ! e B o o k < w w w.woweb o o k . c o m >
Meier02275 ftoc V2 - 03/22/2012
CONTENTS
INTRODUCTION xxxvii
CHAPTER 1: HELLO, ANDROID 1
A Little Background 2
The Not-So-Distant Past 2
Living in the Future 3
What Android Isn’t 3
Android: An Open Platform for Mobile Development 4
Native Android Applications 5
Android SDK Features 6
Access to Hardware, Including Camera, GPS, and Sensors 6
Data Transfers Using Wi-Fi, Bluetooth, and NFC 7
Maps, Geocoding, and Location-Based Services 7
Background Services 7
SQLite Database for Data Storage and Retrieval 8
Shared Data and Inter-Application Communication 8
Using Widgets and Live Wallpaper to Enhance the Home Screen 9
Extensive Media Support and 2D/3D Graphics 9
Cloud to Device Messaging 9
Optimized Memory and Process Management 10
Introducing the Open Handset Alliance 10
What Does Android Run On? 10
Why Develop for Mobile? 11

Why Develop for Android? 11
Factors Driving Android’s Adoption 12
What Android Has That Other Platforms Don’t Have 12
The Changing Mobile Development Landscape 13
Introducing the Development Framework 14
What Comes in the Box 14
Understanding the Android Software Stack 15
The Dalvik Virtual Machine 16
Android Application Architecture 17
Android Libraries 18
ftoc.indd xviiftoc.indd xvii 4/11/2012 10:34:48 AM4/11/2012 10:34:48 AM
Meier02275 ftoc V2 - 03/22/2012
xviii
CONTENTS
CHAPTER 2: GETTING STARTED 19
Developing for Android 20
What You Need to Begin 20
Downloading and Installing the Android SDK 21
Downloading and Installing Updates to the SDK 23
Developing with Eclipse 23
Using the Android Developer Tools Plug-In for Eclipse 24
Using the Support Package 27
Creating Your First Android Application 28
Creating a New Android Project 28
Creating an Android Virtual Device 30
Creating Launch Confi gurations 30
Running and Debugging Your Android Application 33
Understanding Hello World 33
Types of Android Applications 36
Foreground Applications 36

Background Applications 37
Intermittent Applications 37
Widgets and Live Wallpapers 37
Developing for Mobile and Embedded Devices 38
Hardware-Imposed Design Considerations 38
Be E cient 38
Expect Limited Capacity 39
Design for Di erent Screens 39
Expect Low Speeds, High Latency 40
At What Cost? 41
Considering the User’s Environment 42
Developing for Android 43
Being Fast and E cient 43
Being Responsive 44
Ensuring Data Freshness 45
Developing Secure Applications 45
Ensuring a Seamless User Experience 46
Providing Accessibility 47
Android Development Tools 47
The Android Virtual Device Manager 48
Android SDK Manager 49
The Android Emulator 50
ftoc.indd xviiiftoc.indd xviii 4/11/2012 10:34:49 AM4/11/2012 10:34:49 AM
Meier02275 ftoc V2 - 03/22/2012
xix
CONTENTS
The Dalvik Debug Monitor Service 50
The Android Debug Bridge 51
The Hierarchy Viewer and Lint Tool 51
Monkey and Monkey Runner 52

CHAPTER 3: CREATING APPLICATIONS AND ACTIVITIES 53
What Makes an Android Application? 54
Introducing the Application Manifest File 55
A Closer Look at the Application Manifest 56
Using the Manifest Editor 63
Externalizing Resources 64
Creating Resources 65
Simple Values 65
Styles and Themes 68
Drawables 68
Layouts 69
Animations 70
Menus 73
Using Resources 74
Using Resources in Code 74
Referencing Resources Within Resources 75
Using System Resources 76
Referring to Styles in the Current Theme 76
Creating Resources for Di erent Languages and Hardware 77
Runtime Confi guration Changes 79
The Android Application Lifecycle 81
Understanding an Application’s Priority and Its Process’ States 82
Introducing the Android Application Class 83
Extending and Using the Application Class 83
Overriding the Application Lifecycle Events 84
A Closer Look at Android Activities 86
Creating Activities 86
The Activity Lifecycle 87
Activity Stacks 88
Activity States 88

Monitoring State Changes 89
Understanding Activity Lifetimes 91
Android Activity Classes 93
ftoc.indd xixftoc.indd xix 4/11/2012 10:34:49 AM4/11/2012 10:34:49 AM
Meier02275 ftoc V2 - 03/22/2012
xx
CONTENTS
CHAPTER 4: BUILDING USER INTERFACES 95
Fundamental Android UI Design 96
Android User Interface Fundamentals 97
Assigning User Interfaces to Activities 97
Introducing Layouts 98
Defi ning Layouts 99
Using Layouts to Create Device Independent User Interfaces 100
Using a Linear Layout 100
Using a Relative Layout 101
Using a Grid Layout 102
Optimizing Layouts 103
Redundant Layout Containers Are Redundant 103
Avoid Using Excessive Views 105
Using Lint to Analyze Your Layouts 106
To-Do List Example 107
Introducing Fragments 114
Creating New Fragments 115
The Fragment Lifecycle 116
Fragment-Specifi c Lifecycle Events 119
Fragment States 119
Introducing the Fragment Manager 120
Adding Fragments to Activities 120
Using Fragment Transactions 121

Adding, Removing, and Replacing Fragments 122
Using the Fragment Manager to Find Fragments 122
Populating Dynamic Activity Layouts with Fragments 123
Fragments and the Back Stack 124
Animating Fragment Transactions 125
Interfacing Between Fragments and Activities 126
Fragments Without User Interfaces 126
Android Fragment Classes 128
Using Fragments for Your To-Do List 128
The Android Widget Toolbox 132
Creating New Views 133
Modifying Existing Views 133
Customizing Your To-Do List 135
Creating Compound Controls 138
Creating Simple Compound Controls Using Layouts 141
Creating Custom Views 141
Creating a New Visual Interface 142
Handling User Interaction Events 147
ftoc.indd xxftoc.indd xx 4/11/2012 10:34:49 AM4/11/2012 10:34:49 AM
Meier02275 ftoc V2 - 03/22/2012
xxi
CONTENTS
Supporting Accessibility in Custom Views 148
Creating a Compass View Example 149
Using Custom Controls 155
Introducing Adapters 156
Introducing Some Native Adapters 156
Customizing the Array Adapter 156
Using Adapters to Bind Data to a View 158
Customizing the To-Do List Array Adapter 158

Using the Simple Cursor Adapter 162
CHAPTER 5: INTENTS AND BROADCAST RECEIVERS 165
Introducing Intents 166
Using Intents to Launch Activities 166
Explicitly Starting New Activities 167
Implicit Intents and Late Runtime Binding 167
Determining If an Intent Will Resolve 168
Returning Results from Activities 169
Native Android Actions 172
Introducing Linkify 174
Native Linkify Link Types 174
Creating Custom Link Strings 175
Using the Match Filter 176
Using the Transform Filter 176
Using Intents to Broadcast Events 177
Broadcasting Events with Intents 177
Listening for Broadcasts with Broadcast Receivers 178
Broadcasting Ordered Intents 180
Broadcasting Sticky Intents 181
Introducing the Local Broadcast Manager 182
Introducing Pending Intents 182
Creating Intent Filters and Broadcast Receivers 183
Using Intent Filters to Service Implicit Intents 183
How Android Resolves Intent Filters 185
Finding and Using Intents Received Within an Activity 186
Passing on Responsibility 187
Selecting a Contact Example 187
Using Intent Filters for Plug-Ins and Extensibility 193
Supplying Anonymous Actions to Applications 193
Discovering New Actions from Third-Party Intent Receivers 194

Incorporating Anonymous Actions as Menu Items 195
Listening for Native Broadcast Intents 196
ftoc.indd xxiftoc.indd xxi 4/11/2012 10:34:49 AM4/11/2012 10:34:49 AM
Meier02275 ftoc V2 - 03/22/2012
xxii
CONTENTS
Monitoring Device State Changes Using Broadcast Intents 197
Listening for Battery Changes 197
Listening for Connectivity Changes 198
Listening for Docking Changes 199
Managing Manifest Receivers at Run Time 199
CHAPTER 6: USING INTERNET RESOURCES 201
Downloading and Parsing Internet Resources 201
Connecting to an Internet Resource 202
Parsing XML Using the XML Pull Parser 203
Creating an Earthquake Viewer 205
Using the Download Manager 210
Downloading Files 211
Customizing Download Manager Notifi cations 213
Specifying a Download Location 213
Cancelling and Removing Downloads 214
Querying the Download Manager 215
Using Internet Services 217
Connecting to Google App Engine 218
Best Practices for Downloading Data Without Draining
the Battery 219
CHAPTER 7: FILES, SAVING STATE, AND PREFERENCES 221
Saving Simple Application Data 222
Creating and Saving Shared Preferences 222
Retrieving Shared Preferences 223

Creating a Settings Activity for the Earthquake Viewer 223
Introducing the Preference Framework and the
Preference Activity 231
Defi ning a Preference Screen Layout in XML 232
Native Preference Controls 234
Using Intents to Import System Preferences into Preference Screens 234
Introducing the Preference Fragment 235
Defi ning the Preference Fragment Hierarchy
Using Preference Headers 235
Introducing the Preference Activity 236
Backward Compatibility and Preference Screens 237
Finding and Using the Shared Preferences Set by Preference Screens 238
Introducing On Shared Preference Change Listeners 238
ftoc.indd xxiiftoc.indd xxii 4/11/2012 10:34:49 AM4/11/2012 10:34:49 AM
Meier02275 ftoc V2 - 03/22/2012
xxiii
CONTENTS
Creating a Standard Preference Activity for the Earthquake Viewer 238
Persisting the Application Instance State 242
Saving Activity State Using Shared Preferences 242
Saving and Restoring Activity Instance State
Using the Lifecycle Handlers 242
Saving and Restoring Fragment Instance State
Using the Lifecycle Handlers 243
Including Static Files as Resources 245
Working with the File System 246
File-Management Tools 246
Using Application-Specifi c Folders to Store Files 246
Creating Private Application Files 247
Using the Application File Cache 248

Storing Publicly Readable Files 248
CHAPTER 8: DATABASES AND CONTENT PROVIDERS 251
Introducing Android Databases 252
SQLite Databases 252
Content Providers 252
Introducing SQLite 253
Content Values and Cursors 253
Working with SQLite Databases 254
Introducing the SQLiteOpenHelper 255
Opening and Creating Databases Without the SQLite Open Helper 257
Android Database Design Considerations 257
Querying a Database 257
Extracting Values from a Cursor 259
Adding, Updating, and Removing Rows 260
Inserting Rows 260
Updating Rows 261
Deleting Rows 261
Creating Content Providers 262
Registering Content Providers 262
Publishing Your Content Provider’s URI Address 263
Creating the Content Provider’s Database 264
Implementing Content Provider Queries 264
Content Provider Transactions 266
Storing Files in a Content Provider 268
A Skeleton Content Provider Implementation 270
ftoc.indd xxiiiftoc.indd xxiii 4/11/2012 10:34:49 AM4/11/2012 10:34:49 AM

×