Professional Android 2 Application Development: • Reviews Android as a development platform and best practices for mobile development • Provides an in-depth look at the Android applicat
Trang 1Wrox Programmer to Programmer™
Join the discussion @ p2p.wrox.com
Written by an Android authority, this up-to-date resource shows you
how to leverage the features of Android 2 to enhance existing
products or create innovative new ones Serving as a hands-on guide
to building mobile apps using Android, the book walks you through
a series of sample projects that introduces you to Android’s new features
and techniques Using the explanations and examples included in
these pages, you’ll acquire the foundation needed to write compelling
mobile applications that use Android, along with the flexibility to
quickly adapt to future enhancements.
Professional Android 2 Application Development:
• Reviews Android as a development platform and best practices
for mobile development
• Provides an in-depth look at the Android application components
• Details creating layouts and Views to produce compelling resolution
independent user interfaces
• Examines Intents and Content Providers for sharing data
• Introduces techniques for creating map-based applications and using
location-based services such as GPS
• Looks at how to create and use background Services, Notifications,
and Alarms
• Demonstrates how to create interactive homescreen components
• Explores the Bluetooth, telephony, and networking APIs
• Examines using hardware, including the camera and sensors such
as the compass and accelerometers
Reto Meier is a software developer who has been involved in Android since the
initial release in 2007 He is an Android Developer Advocate at Google
Wrox Professional guides are planned and written by working programmers
to meet the real-world needs of programmers, developers, and IT professionals
Focused and relevant, they address the issues technology professionals face every
day They provide examples, practical solutions, and expert education in new
technologies, all designed to help programmers do a better job
Programming / Mobile & Wireless / Android
Build unique mobile applications
with the latest Android SDK
wrox.com Programmer Forums
Join our Programmer to Programmer forums to ask and answer programming questions about this book, join discussions on the hottest topics in the industry, and connect with fellow programmers from around the world
Code Downloads
Take advantage of free code samples from this book, as well as code samples from hundreds of other books, all ready to use
Read More
Find articles, ebooks, sample chapters and tables of contents for hundreds of books, and more reference resources on programming topics that matter
to you
$44.99 USA $53.99 CAN
Trang 2Related Wrox Books
Beginning iPhone SDK Programming with Objective-C
ISBN: 9780470500972Learning to develop iPhone applications doesn’t need to be an overwhelming undertaking This book provides an easy-to-follow, example-driven introduction to the fundamentals of the Apple iPhone SDK and offers you a clear understanding of how things are done when programming iPhone applications with Objective-C When you reach the end of the book, you will be prepared to confidently tackle your next iPhone programming challenge
Ivor Horton’s Beginning Java 2: JDK 5 Edition
ISBN: 978-0-7645-6874-9This comprehensive introduction to Java programming — written by the leading author of computer programming language tutorials — shows readers how to build real-world Java applications using the Java SDK (software development kit)
Safari and WebKit Development for iPhone OS 3.0
ISBN: 9780470549667With the unparalleled success of iPhone and iPod touch, iPhone OS 3.0 has emerged as a compelling platform for which vast numbers of web developers are designing and building web-based mobile applications This book explores the Safari and WebKit development platform that is built into iPhone OS 3.0 and takes you through the process of creating an iPhone web application from the ground up You’ll learn how to use existing open source frameworks to speed up your development time, imitate qualities
of built-in Apple apps, cache data locally and even run in offline mode, and more Whether you’re eager to build new web applications for iPhone OS 3.0 or optimize existing web sites for this platform, you have everything you need to do so within this book
Get more out of
Wrox Online Library
Hundreds of our books are available online
through Books24x7.com
Wrox Blox
Download short informational pieces and code
to keep you up to date and out of trouble!
Join the Community
Sign up for our free monthly newsletter at newsletter.wrox.com
Browse
Ready for more Wrox? We have books and e-books available on NET, SQL Server, Java, XML, Visual Basic, C#/ C++, and much more!
Contact Us
We always like to get feedback from our readers Have a book idea?
Need community support? Let us know by e-mailing wrox-partnerwithus@wrox.com
Trang 3ANDROID™ 2 APPLICATION DEVELOPMENT
INTRODUCTION xxvii
CHAPTER 1 Hello, Android 1
CHAPTER 2 Getting Started 17
CHAPTER 3 Creating Applications and Activities 49
CHAPTER 4 Creating User Interfaces 85
CHAPTER 5 Intents, Broadcast Receivers, Adapters, and the Internet 137
CHAPTER 6 Files, Saving State, and Preferences 187
CHAPTER 7 Databases and Content Providers 209
CHAPTER 8 Maps, Geocoding, and Location-Based Services 245
CHAPTER 9 Working in the Background 285
CHAPTER 10 Invading the Phone-Top 327
CHAPTER 11 Audio, Video, and Using the Camera 363
CHAPTER 12 Telephony and SMS 389
CHAPTER 13 Bluetooth, Networks, and Wi-Fi 425
CHAPTER 14 Sensors 457
CHAPTER 15 Advanced Android Development 477
INDEX 529
Trang 6Professional Android™2 Application Development
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 also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic books.
Library of Congress Control Number: 2009943638
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 affiliates, 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 Wiley Publishing, Inc is not associated with any product or vendor mentioned in this book.
Trang 7To Kristy
Trang 9ABOUT THE AUTHOR
RETO MEIERis originally from Perth, Western Australia, but now lives in London
He currently works as an Android Developer Advocate at Google, helping Android app ers create the best applications possible Reto is an experienced software developer with more than
develop-10 years of experience in GUI application development Before Google, he worked in various tries, including offshore oil and gas and finance
indus-Always interested in emerging technologies, Reto has been involved in Android since the initialrelease in 2007 In his spare time, he tinkers with a wide range of development platforms, includingGoogle’s plethora of developer tools
You can check out Reto’s web site, The Radioactive Yak, athttp://blog.radioactiveyak.comorfollow him on twitter athttp://www.twitter.com/retomeier
ABOUT THE TECHNICAL EDITOR
MILAN NARENDRA SHAHgraduated with a BSc Computer Science degree from the University ofSouthampton He has been working as a software engineer for more than seven years, with
experiences in C#, C/C++, and Java He is married and lives in Buckinghamshire, United Kingdom
Trang 11Mary Beth Wakefield
ASSOCIATE DIRECTOR OF MARKETING
Trang 13Most importantly I’d like to thank Kristy Your support makes everything I do possible, and yourgenerous help ensured that this book was the best it could be Without you it would never havehappened
A big thank-you goes to Google and the Android team, particularly the Android engineers and mycolleagues in developer relations The pace at which Android has grown and developed in the pastyear is nothing short of phenomenal
I also thank Scott Meyers for giving me the chance to bring this book up to date; and Bill Bridges,Milan Shah, Sadie Kleinman, and the Wrox team for helping get it done
Special thanks go out to the Android developer community Your hard work and exciting tions have helped make Android a great success
Trang 15INTRODUCTION xxvii CHAPTER 1: HELLO, ANDROID 1
Android: An Open Platform for Mobile Development 4
Extensive Media Support and 2D/3D Graphics 8Optimized Memory and Process Management 8
Introducing the Open Handset Alliance 9
What Has and Will Continue to Drive Android Adoption? 10What Does It Have That Others Don’t? 11Changing the Mobile Development Landscape 11
Introducing the Development Framework 12
Understanding the Android Software Stack 13The Dalvik Virtual Machine 14Android Application Architecture 15
Trang 16CHAPTER 2: GETTING STARTED 17
Downloading and Installing the SDK 18
Using the Eclipse Plug-In 20Creating Your First Android Application 23Starting a New Android Project 23Creating a Launch Configuration 24Running and Debugging Your Android Applications 26Understanding Hello World 26Types of Android Applications 29
Background Services and Intent Receivers 29Intermittent Applications 30
Developing for Mobile Devices 30
Hardware-Imposed Design Considerations 30
Expect Low Speeds, High Latency 32
Considering the Users’ Environment 34
Developing Secure Applications 37Ensuring a Seamless User Experience 37
The Android Virtual Device and SDK Manager 44
Dalvik Debug Monitor Service (DDMS) 47The Android Debug Bridge (ADB) 47
Trang 17CHAPTER 3: CREATING APPLICATIONS AND ACTIVITIES 49
What Makes an Android Application? 50
Introducing the Application Manifest 51
The Android Application Life Cycle 57
Understanding Application Priority and Process States 58
Referencing Resources within Resources 68
Referring to Styles in the Current Theme 70
To-Do List Resources Example 70
Creating Resources for Different Languages and Hardware 71
Runtime Configuration Changes 72
Introducing the Android Application Class 74
Extending and Using the Application Class 74
Overriding the Application Life Cycle Events 75
A Closer Look at Android Activities 76
Understanding Activity Lifetimes 82
CHAPTER 4: CREATING USER INTERFACES 85
Fundamental Android UI Design 86
Trang 18Creating Activity User Interfaces with Views 87The Android Widget Toolbox 88
Customizing Your To-Do List 93Creating Compound Controls 96
Creating a New Visual Interface 99Handling User Interaction Events 104Creating a Compass View Example 105
Resolution and Density Independence 117
The Resource Framework and Resolution Independence 118Resource Qualifiers for Screen Size and Pixel Density 118Specifying Supported Screen Sizes 119Best Practices for Resolution Independence 119Relative Layouts and Density-Independent Pixels 120Using Scalable Graphics Assets 120Provide Optimized Resources for Different Screens 121Testing, Testing, Testing 121
Testing for Custom Resolutions and Screen Sizes 122
Introducing the Android Menu System 123
Trang 19Dynamically Updating Menu Items 127
Submenus and Context Menus 128
CHAPTER 5: INTENTS, BROADCAST RECEIVERS, ADAPTERS,
AND THE INTERNET 137
Using Intents to Launch Activities 138
Explicitly Starting New Activities 139
Implicit Intents and Late Runtime Binding 139
Returning Results from Activities 140
Using Intent Filters to Service Implicit Intents 144
How Android Resolves Intent Filters 146
Finding and Using the Launch Intent Within an Activity 147
Passing on Responsibility 147
Select a Contact Example 148
Using Intent Filters for Plug-Ins and Extensibility 152
Supplying Anonymous Actions to Applications 153
Incorporating Anonymous Actions in Your Activity’s Menu 154
The Native Linkify Link Types 155
Creating Custom Link Strings 156
Using the Transform Filter 157
Using Intents to Broadcast Events 157
Broadcasting Events with Intents 158
Listening for Broadcasts with Broadcast Receivers 158
Broadcasting Sticky and Ordered Intents 161
Native Android Broadcast Actions 161
Introducing Pending Intents 162
Introducing Some Native Adapters 163
Customizing the Array Adapter 163
Using Adapters for Data Binding 164
Trang 20Customizing the To-Do List Array Adapter 165Using the Simple Cursor Adapter 169
Connecting to an Internet Resource 170
Introducing the Dialog Classes 172
Specialist Input Dialogs 174Using Activities as Dialogs 174Managing and Displaying Dialogs 175
Creating an Earthquake Viewer 176
CHAPTER 6: FILES, SAVING STATE, AND PREFERENCES 187
Saving Simple Application Data 188 Creating and Saving Preferences 188 Retrieving Shared Preferences 189 Creating a Settings Activity for the Earthquake Viewer 189 Introducing the Preference Activity and Preferences Framework 197
Defining a Preference Screen Layout in XML 198Native Preference Controls 199Using Intents to Import System Preference Screens 200Introducing the Preference Activity 200Finding and Using Preference Screen Shared Preferences 201Introducing Shared Preference Change Listeners 201
Creating a Standard Preference Activity for the Earthquake Viewer 202
Saving and Restoring Instance State 203Saving the To-Do List Activity State 205
Including Static Files as Resources 207
CHAPTER 7: DATABASES AND CONTENT PROVIDERS 209
Introducing Android Databases 209
Introducing SQLite Databases 210Introducing Content Providers 210
Trang 21Introducing SQLite 210
Cursors and Content Values 211
Working with SQLite Databases 211
Introducing the SQLiteOpenHelper 214
Opening and Creating Databases without SQLiteHelper 215
Android Database Design Considerations 215
Extracting Results from a Cursor 216
Adding, Updating, and Removing Rows 217
Creating a New Content Provider 224
Exposing Access to the Data Source 225
Registering Your Provider 227
Introducing Content Resolvers 227
Adding, Updating, and Deleting Content 228
Accessing Files in Content Providers 230
Creating and Using an Earthquake Content Provider 230
Creating the Content Provider 230
Native Android Content Providers 238
Using the Media Store Provider 239
Using the Contacts Provider 240
Introducing the Contacts Contract Content Provider 240
Modifying and Augmenting Contact Details 243
CHAPTER 8: MAPS, GEOCODING, AND LOCATION-BASED SERVICES 245
Using Location-Based Services 246
Configuring the Emulator to Test Location-Based Services 246
Updating Locations in Emulator Location Providers 246
Trang 22Selecting a Location Provider 247
Finding the Available Providers 248Finding Location Providers Using Criteria 248
Updating Your Location in ‘Where Am I?’ 253
Creating Map-Based Activities 260
Introducing Map View and Map Activity 260Getting Your Maps API Key 261Getting Your Development/Debugging MD5 Fingerprint 261Getting your Production/Release MD5 Fingerprint 262Creating a Map-Based Activity 262Configuring and Using Map Views 263
Creating and Using Overlays 268
Drawing on the Overlay Canvas 269
Adding and Removing Overlays 271Annotating ‘Where Am I?’ 271Introducing My Location Overlay 275Introducing Itemized Overlays and Overlay Items 275Pinning Views to the Map and Map Positions 278
Mapping Earthquakes Example 279
Trang 23Starting, Controlling, and Interacting with a Service 290
An Earthquake Monitoring Service Example 290
Binding Activities to Services 297
Prioritizing Background Services 299
Using AsyncTask to Run Asynchronous Tasks 301
Creating a New Asynchronous Task 301
Running an Asynchronous Task 302
Moving the Earthquake Service to a Background Thread Using AsyncTask 303
Manual Thread Creation and GUI Thread Synchronization 304
Using the Handler for Performing GUI Operations 304
Creating a Notification and Configuring the Status Bar Icon 310
Configuring the Extended Status Notification Display 311
Adding Notifications and Toasts to the Earthquake Monitor 314
Advanced Notification Techniques 316
Ongoing and Insistent Notifications 319
Using Repeating Alarms to Update Earthquakes 323
CHAPTER 10: INVADING THE PHONE-TOP 327
Introducing Home-Screen Widgets 328
Creating the Widget Layout 329
Widget Design Guidelines 329
Supported Widget Views and Layouts 330
Defining Your Widget Settings 331
Trang 24Creating Your Widget Intent Receiver and Adding It to the
Using the Minimum Update Rate 337
Creating and Using a Widget Configuration Activity 340
Creating an Earthquake Widget 341
Live Folder Content Providers 347
Creating an Earthquake Live Folder 349
Adding Search to Your Applications and the Quick Search Box 351
Adding Search to Your Application 351Creating a Search Activity 352Responding to Search Queries from a Content Provider 353Surfacing Search Results to the Quick Search Box 355Adding Search to the Earthquake Example 355
Creating a Live Wallpaper Definition Resource 359Creating a Wallpaper Service 359Creating a Wallpaper Service Engine 360
CHAPTER 11: AUDIO, VIDEO, AND USING THE CAMERA 363
Introducing the Media Player 364Preparing Audio for Playback 365Packaging Audio as an Application Resource 365Initializing Audio Content for Playback 365Preparing for Video Playback 366Playing Video Using the Video View 367
Trang 25Setting up a Surface for Video Playback 367
Initializing Video Content for Playback 369
Managing Media Playback Output 370
Using Intents to Record Video 371
Configuring and Controlling Video Recording 373
Previewing Video Recording 374
Using the Camera and Taking Pictures 375
Using Intents to Take Pictures 375
Controlling the Camera and Taking Pictures 377
Controlling and Monitoring Camera Settings and Image Options 377
Using the Camera Preview 379
Reading and Writing JPEG EXIF Image Details 381
Adding New Media to the Media Store 382
Inserting Media into the Media Store 383
Recording Sound with Audio Record 384
Playing Sound with Audio Track 385
CHAPTER 12: TELEPHONY AND SMS 389
Launching the Dialer to Initiate Phone Calls 390
Replacing the Native Dialer 390
Accessing Phone and Network Properties and Status 392
Reading Phone Device Details 392
Reading Data Connection and Transfer State 392
Monitoring Changes in Phone State, Phone Activity, and
Monitoring Incoming Phone Calls 396
Tracking Cell Location Changes 396
Tracking Service Changes 397
Monitoring Data Connectivity and Activity 398