Your SlideShare is downloading. ×
Professional android 4 application development [www.itepress.com]
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Professional android 4 application development [www.itepress.com]

5,079
views

Published on

Professional android 4 application development [Upload by www.itepress.com]

Professional android 4 application development [Upload by www.itepress.com]

Published in: Education

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
5,079
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
346
Comments
0
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. www.it-ebooks.info
  • 2. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd ii 4/11/2012 10:37:19 AM
  • 3. 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.infoffirs.indd i 4/11/2012 10:37:18 AM
  • 4. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd ii 4/11/2012 10:37:19 AM
  • 5. 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
  • 6. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd iv 4/11/2012 10:37:19 AM
  • 7. Meier02275 ffirs V2 - 03/22/2012 PROFESSIONAL Android™ 4 Application Development Reto Meier www.it-ebooks.infoffirs.indd v 4/11/2012 10:37:19 AM
  • 8. 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 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.infoffirs.indd vi 4/11/2012 10:37:21 AM
  • 9. 10 Meier02275 ffirs V2 - 03/22/2012 To Kris www.it-ebooks.info ffirs.indd vii 4/11/2012 10:37:21 AM
  • 10. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd viii 4/11/2012 10:37:21 AM
  • 11. 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 (http://blog.radioactiveyak.com), 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
  • 12. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd x 4/11/2012 10:37:22 AM
  • 13. 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
  • 14. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd xii 4/11/2012 10:37:22 AM
  • 15. 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 John Sleeva PUBLISHER 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
  • 16. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd xiv 4/11/2012 10:37:22 AM
  • 17. 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
  • 18. Meier02275 ffirs V2 - 03/22/2012 www.it-ebooks.infoffirs.indd xvi 4/11/2012 10:37:22 AM
  • 19. 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 www.it-ebooks.infoftoc.indd xvii 4/11/2012 10:34:48 AM
  • 20. Meier02275 ftoc V2 - 03/22/2012 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 Configurations 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 Efficient 38 Expect Limited Capacity 39 Design for Different 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 Efficient 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 xviii www.it-ebooks.infoftoc.indd xviii 4/11/2012 10:34:49 AM
  • 21. Meier02275 ftoc V2 - 03/22/2012 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 Different Languages and Hardware 77 Runtime Configuration 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 xix www.it-ebooks.infoftoc.indd xix 4/11/2012 10:34:49 AM
  • 22. Meier02275 ftoc V2 - 03/22/2012 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 Defining 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-Specific 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 xx www.it-ebooks.infoftoc.indd xx 4/11/2012 10:34:49 AM
  • 23. Meier02275 ftoc V2 - 03/22/2012 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 xxi www.it-ebooks.infoftoc.indd xxi 4/11/2012 10:34:49 AM
  • 24. Meier02275 ftoc V2 - 03/22/2012 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 Notifications 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 Defining 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 Defining 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 xxii www.it-ebooks.infoftoc.indd xxii 4/11/2012 10:34:49 AM
  • 25. Meier02275 ftoc V2 - 03/22/2012 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-Specific 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 xxiii www.it-ebooks.infoftoc.indd xxiii 4/11/2012 10:34:49 AM
  • 26. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Using Content Providers 274 Introducing the Content Resolver 274 Querying Content Providers 274 Querying for Content Asynchronously Using the Cursor Loader 277 Introducing Loaders 277 Using the Cursor Loader 277 Adding, Deleting, and Updating Content 280 Inserting Content 280 Deleting Content 281 Updating Content 281 Accessing Files Stored in Content Providers 282 Creating a To-Do List Database and Content Provider 283 Adding Search to Your Application 290 Making Your Content Provider Searchable 291 Creating a Search Activity for Your Application 292 Making Your Search Activity the Default Search Provider for Your Application 293 Performing a Search and Displaying the Results 294 Using the Search View Widget 297 Supporting Search Suggestions from a Content Provider 298 Surfacing Search Results in the Quick Search Box 301 Creating a Searchable Earthquake Content Provider 301 Creating the Content Provider 302 Using the Earthquake Provider 307 Searching the Earthquake Provider 310 Native Android Content Providers 316 Using the Media Store Content Provider 317 Using the Contacts Contract Content Provider 318 Introducing the Contacts Contract Content Provider 318 Reading Contact Details 319 Creating and Picking Contacts Using Intents 323 Modifying and Augmenting Contact Details Directly 324 Using the Calendar Content Provider 325 Querying the Calendar 325 Creating and Editing Calendar Entries Using Intents 327 Modifying Calendar Entries Directly 329 CHAPTER 9: WORKING IN THE BACKGROUND 331 Introducing Services 332 Creating and Controlling Services 332 Creating Services 332 xxiv www.it-ebooks.infoftoc.indd xxiv 4/11/2012 10:34:49 AM
  • 27. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Executing a Service and Controlling Its Restart Behavior 333 Starting and Stopping Services 335 Self-Terminating Services 336 Binding Services to Activities 336 An Earthquake-Monitoring Service Example 338 Creating Foreground Services 343 Using Background Threads 345 Using AsyncTask to Run Asynchronous Tasks 345 Creating New Asynchronous Tasks 346 Running Asynchronous Tasks 347 Introducing the Intent Service 348 Introducing Loaders 349 Manual Thread Creation and GUI Thread Synchronization 349 Using Alarms 351 Creating, Setting, and Canceling Alarms 352 Setting Repeating Alarms 353 Using Repeating Alarms to Schedule Network Refreshes 354 Using the Intent Service to Simplify the Earthquake Update Service 357 CHAPTER 10: EXPANDING THE USER EXPERIENCE 359 Introducing the Action Bar 360 Customizing the Action Bar 362 Modifying the Icon and Title Text 362 Customizing the Background 363 Enabling the Split Action Bar Mode 364 Customizing the Action Bar to Control Application Navigation Behavior 364 Configuring Action Bar Icon Navigation Behavior 365 Using Navigation Tabs 366 Using Drop-Down Lists for Navigation 368 Using Custom Navigation Views 370 Introducing Action Bar Actions 370 Adding an Action Bar to the Earthquake Monitor 370 Creating and Using Menus and Action Bar Action Items 377 Introducing the Android Menu System 377 Creating a Menu 379 Specifying Action Bar Actions 380 Menu Item Options 381 Adding Action Views and Action Providers 382 Adding Menu Items from Fragments 383 Defining Menu Hierarchies in XML 384 xxv www.it-ebooks.infoftoc.indd xxv 4/11/2012 10:34:49 AM
  • 28. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Updating Menu Items Dynamically 385 Handling Menu Selections 386 Introducing Submenus and Context Menus 387 Creating Submenus 387 Using Context Menus and Popup Menus 388 Refreshing the Earthquake Monitor 390 Going Full Screen 392 Introducing Dialogs 394 Creating a Dialog 395 Using the Alert Dialog Class 396 Using Specialized Input Dialogs 397 Managing and Displaying Dialogs Using Dialog Fragments 398 Managing and Displaying Dialogs Using Activity Event Handlers 400 Using Activities as Dialogs 401 Let’s Make a Toast 401 Customizing Toasts 402 Using Toasts in Worker Threads 404 Introducing Notifications 405 Introducing the Notification Manager 406 Creating Notifications 407 Creating a Notification and Configuring the Status Bar Display 407 Using the Default Notification Sounds, Lights, and Vibrations 408 Making Sounds 408 Vibrating the Device 409 Flashing the Lights 409 Using the Notification Builder 410 Setting and Customizing the Notification Tray UI 410 Using the Standard Notification UI 411 Creating a Custom Notification UI 412 Customizing the Ticker View 414 Configuring Ongoing and Insistent Notifications 415 Triggering, Updating, and Canceling Notifications 416 Adding Notifications and Dialogs to the Earthquake Monitor 418 CHAPTER 11: ADVANCED USER EXPERIENCE 425 Designing for Every Screen Size and Density 426 Resolution Independence 426 Using Density-Independent Pixels 426 Resource Qualifiers for Pixel Density 427 xxvi www.it-ebooks.infoftoc.indd xxvi 4/11/2012 10:34:49 AM
  • 29. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Supporting and Optimizing for Different Screen Sizes 427 Creating Scalable Layouts 428 Optimizing Layouts for Different Screen Types 428 Specifying Supported Screen Sizes 430 Creating Scalable Graphics Assets 431 Color Drawables 431 Shape Drawables 431 Gradient Drawables 432 NinePatch Drawables 434 Creating Optimized, Adaptive, and Dynamic Designs 434 Testing, Testing, Testing 435 Using Emulator Skins 435 Testing for Custom Resolutions and Screen Sizes 435 Ensuring Accessibility 436 Supporting Navigation Without a Touch Screen 436 Providing a Textual Description of Each View 436 Introducing Android Text-to-Speech 437 Using Speech Recognition 439 Using Speech Recognition for Voice Input 440 Using Speech Recognition for Search 441 Controlling Device Vibration 441 Working with Animations 442 Tweened View Animations 442 Creating Tweened View Animations 443 Applying Tweened Animations 443 Using Animation Listeners 444 Animating Layouts and View Groups 444 Creating and Using Frame-by-Frame Animations 445 Interpolated Property Animations 446 Creating Property Animations 447 Creating Property Animation Sets 449 Using Animation Listeners 449 Enhancing Your Views 450 Advanced Canvas Drawing 450 What Can You Draw? 450 Getting the Most from Your Paint 451 Improving Paint Quality with Anti-Aliasing 456 Canvas Drawing Best Practice 457 Advanced Compass Face Example 458 xxvii www.it-ebooks.infoftoc.indd xxvii 4/11/2012 10:34:49 AM
  • 30. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Hardware Acceleration 466 Managing Hardware Acceleration Use in Your Applications 466 Checking If Hardware Acceleration Is Enabled 467 Introducing the Surface View 467 When to Use a Surface View 467 Creating Surface Views 468 Creating 3D Views with a Surface View 470 Creating Interactive Controls 470 Using the Touch Screen 471 Using the Device Keys, Buttons, and D-Pad 475 Using the On Key Listener 475 Using the Trackball 476 Advanced Drawable Resources 476 Composite Drawables 476 Transformative Drawables 476 Layer Drawables 477 State List Drawables 478 Level List Drawables 479 Copy, Paste, and the Clipboard 479 Copying Data to the Clipboard 479 Pasting Clipboard Data 480 CHAPTER 12: HARDWARE SENSORS 481 Using Sensors and the Sensor Manager 482 Supported Android Sensors 482 Introducing Virtual Sensors 483 Finding Sensors 484 Monitoring Sensors 485 Interpreting Sensor Values 487 Monitoring a Device’s Movement and Orientation 489 Determining the Natural Orientation of a Device 490 Introducing Accelerometers 491 Detecting Acceleration Changes 492 Creating a Gravitational Force Meter 494 Determining a Device’s Orientation 497 Understanding the Standard Reference Frame 497 Calculating Orientation Using the Accelerometer and Magnetic Field Sensors 498 Remapping the Orientation Reference Frame 500 Determining Orientation Using the Deprecated Orientation Sensor 501 xxviii www.it-ebooks.infoftoc.indd xxviii 4/11/2012 10:34:49 AM
  • 31. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Creating a Compass and Artificial Horizon 502 Introducing the Gyroscope Sensor 505 Introducing the Environmental Sensors 506 Using the Barometer Sensor 506 Creating a Weather Station 508 CHAPTER 13: MAPS, GEOCODING, AND LOCATION-BASED SERVICES 513 Using Location-Based Services 514 Using the Emulator with Location-Based Services 515 Updating Locations in Emulator Location Providers 515 Configuring the Emulator to Test Location-Based Services 516 Selecting a Location Provider 516 Finding Location Providers 517 Finding Location Providers by Specifying Criteria 517 Determining Location Provider Capabilities 518 Finding Your Current Location 519 Location Privacy 519 Finding the Last Known Location 519 Where Am I Example 519 Refreshing the Current Location 522 Tracking Your Location in Where Am I 525 Requesting a Single Location Update 527 Best Practice for Location Updates 527 Monitoring Location Provider Status and Availability 528 Using Proximity Alerts 530 Using the Geocoder 532 Reverse Geocoding 533 Forward Geocoding 534 Geocoding Where Am I 535 Creating Map-Based Activities 536 Introducing Map View and Map Activity 537 Getting Your Maps API Key 537 Getting Your Development/Debugging MD5 Fingerprint 537 Getting your Production/Release MD5 Fingerprint 538 Creating a Map-Based Activity 538 Maps and Fragments 540 Configuring and Using Map Views 541 Using the Map Controller 541 Mapping Where Am I 542 xxix www.it-ebooks.infoftoc.indd xxix 4/11/2012 10:34:50 AM
  • 32. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Creating and Using Overlays 546 Creating New Overlays 546 Introducing Projections 547 Drawing on the Overlay Canvas 547 Handling Map Tap Events 548 Adding and Removing Overlays 549 Annotating Where Am I 549 Introducing My Location Overlay 553 Introducing Itemized Overlays and Overlay Items 554 Pinning Views to the Map and Map Positions 556 Mapping Earthquakes Example 558 CHAPTER 14: INVADING THE HOME SCREEN 565 Introducing Home Screen Widgets 566 Creating App Widgets 567 Creating the Widget XML Layout Resource 567 Widget Design Guidelines 567 Supported Widget Views and Layouts 568 Defining Your Widget Settings 569 Creating Your Widget Intent Receiver and Adding It to the Application Manifest 570 Introducing the App Widget Manager and Remote Views 572 Creating and Manipulating Remote Views 572 Applying Remote Views to Running App Widgets 574 Using Remote Views to Add Widget Interactivity 575 Refreshing Your Widgets 577 Using the Minimum Update Rate 577 Using Intents 578 Using Alarms 579 Creating and Using a Widget Configuration Activity 580 Creating an Earthquake Widget 582 Introducing Collection View Widgets 587 Creating Collection View Widget Layouts 589 Creating the Remote Views Service 591 Creating a Remote Views Factory 591 Populating Collection View Widgets Using a Remote Views Service 594 Adding Interactivity to the Items Within a Collection View Widget 595 Binding Collection View Widgets to Content Providers 596 Refreshing Your Collection View Widgets 598 Creating an Earthquake Collection View Widget 598 xxx www.it-ebooks.infoftoc.indd xxx 4/11/2012 10:34:50 AM
  • 33. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Introducing Live Folders 605 Creating Live Folders 606 The Live Folder Content Provider 606 The Live Folder Activity 608 Creating an Earthquake Live Folder 610 Surfacing Application Search Results Using the Quick Search Box 614 Surfacing Search Results to the Quick Search Box 614 Adding the Earthquake Example Search Results to the Quick Search Box 615 Creating Live Wallpaper 616 Creating a Live Wallpaper Definition Resource 616 Creating a Wallpaper Service 617 Creating a Wallpaper Service Engine 618 CHAPTER 15: AUDIO, VIDEO, AND USING THE CAMERA 621 Playing Audio and Video 622 Introducing the Media Player 623 Preparing Audio for Playback 624 Initializing Audio Content for Playback 624 Preparing Video for Playback 625 Playing Video Using the Video View 625 Creating a Surface for Video Playback 626 Controlling Media Player Playback 629 Managing Media Playback Output 631 Responding to the Volume Controls 631 Responding to the Media Playback Controls 632 Requesting and Managing Audio Focus 635 Pausing Playback When the Output Changes 637 Introducing the Remote Control Client 637 Manipulating Raw Audio 640 Recording Sound with Audio Record 640 Playing Sound with Audio Track 642 Creating a Sound Pool 643 Using Audio Effects 645 Using the Camera for Taking Pictures 646 Using Intents to Take Pictures 646 Controlling the Camera Directly 648 Camera Properties 648 Camera Settings and Image Parameters 649 Controlling Auto Focus, Focus Areas, and Metering Areas 650 xxxi www.it-ebooks.infoftoc.indd xxxi 4/11/2012 10:34:50 AM
  • 34. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Using the Camera Preview 651 Detecting Faces and Facial Features 653 Taking a Picture 654 Reading and Writing JPEG EXIF Image Details 655 Recording Video 656 Using Intents to Record Video 656 Using the Media Recorder to Record Video 657 Configuring the Video Recorder 658 Previewing the Video Stream 660 Controlling the Recording 660 Creating a Time-Lapse Video 661 Using Media Effects 661 Adding Media to the Media Store 662 Inserting Media Using the Media Scanner 662 Inserting Media Manually 663 CHAPTER 16: BLUETOOTH, NFC, NETWORKS, AND WI-FI 665 Using Bluetooth 666 Managing the Local Bluetooth Device Adapter 666 Being Discoverable and Remote Device Discovery 669 Managing Device Discoverability 669 Discovering Remote Devices 671 Bluetooth Communications 673 Opening a Bluetooth Server Socket Listener 674 Selecting Remote Bluetooth Devices for Communications 675 Opening a Client Bluetooth Socket Connection 676 Transmitting Data Using Bluetooth Sockets 677 Managing Network and Internet Connectivity 679 Introducing the Connectivity Manager 679 Supporting User Preferences for Background Data Transfers 679 Finding and Monitoring Network Connectivity 681 Managing Wi-Fi 682 Monitoring Wi-Fi Connectivity 683 Monitoring Active Wi-Fi Connection Details 684 Scanning for Hotspots 684 Managing Wi-Fi Configurations 685 Creating Wi-Fi Network Configurations 685 Transferring Data Using Wi-Fi Direct 686 Initializing the Wi-Fi Direct Framework 686 Enabling Wi-Fi Direct and Monitoring Its Status 688 xxxii www.it-ebooks.infoftoc.indd xxxii 4/11/2012 10:34:50 AM
  • 35. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Discovering Peers 689 Connecting with Peers 690 Transferring Data Between Peers 692 Near Field Communication 693 Reading NFC Tags 693 Using the Foreground Dispatch System 695 Introducing Android Beam 697 Creating Android Beam Messages 697 Assigning the Android Beam Payload 699 Receiving Android Beam Messages 699 CHAPTER 17: TELEPHONY AND SMS 701 Hardware Support for Telephony 701 Marking Telephony as a Required Hardware Feature 702 Checking for Telephony Hardware 702 Using Telephony 702 Initiating Phone Calls 703 Replacing the Native Dialer 703 Accessing Telephony Properties and Phone State 705 Reading Phone Device Details 705 Reading Network Details 706 Reading SIM Details 707 Reading Data Connection and Transfer State Details 707 Monitoring Changes in Phone State Using the Phone State Listener 708 Monitoring Incoming Phone Calls 709 Tracking Cell Location Changes 710 Tracking Service Changes 710 Monitoring Data Connectivity and Data Transfer Status Changes 711 Using Intent Receivers to Monitor Incoming Phone Calls 712 Introducing SMS and MMS 713 Using SMS and MMS in Your Application 713 Sending SMS and MMS from Your Application Using Intents 713 Sending SMS Messages Using the SMS Manager 714 Sending Text Messages 715 Tracking and Confirming SMS Message Delivery 715 Conforming to the Maximum SMS Message Size 717 Sending Data Messages 717 Listening for Incoming SMS Messages 717 Simulating Incoming SMS Messages in the Emulator 719 Handling Data SMS Messages 719 xxxiii www.it-ebooks.infoftoc.indd xxxiii 4/11/2012 10:34:50 AM
  • 36. Meier02275 ftoc V2 - 03/22/2012 CONTENTS Emergency Responder SMS Example 720 Automating the Emergency Responder 729 Introducing SIP and VOIP 737 CHAPTER 18: ADVANCED ANDROID DEVELOPMENT 739 Paranoid Android 740 Linux Kernel Security 740 Introducing Permissions 740 Declaring and Enforcing Permissions 741 Enforcing Permissions when Broadcasting Intents 742 Introducing Cloud to Device Messaging 743 C2DM Restrictions 743 Signing Up to Use C2DM 744 Registering Devices with a C2DM Server 744 Sending C2DM Messages to Devices 748 Receiving C2DM Messages 749 Implementing Copy Protection Using the License Verification Library 750 Installing the License Verification Library 750 Finding Your License Verification Public Key 751 Configuring Your License Validation Policy 751 Performing License Validation Checks 752 Introducing In-App Billing 753 In-App Billing Restrictions 754 Installing the In-App Billing Library 754 Finding Your Public Key and Defining Your Purchasable Items 754 Initiating In-App Billing Transactions 755 Handling In-App Billing Purchase Request Responses 756 Using Wake Locks 757 Using AIDL to Support Inter-Process Communication for Services 759 Implementing an AIDL Interface 759 Making Classes Parcelable 759 Creating an AIDL Service Definition 762 Implementing and Exposing the AIDL Service Definition 762 Dealing with Different Hardware and Software Availability 765 Specifying Hardware as Required 766 Confirming Hardware Availability 766 Building Backward-Compatible Applications 766 Parallel Activities 767 Interfaces and Fragments 768 Optimizing UI Performance with Strict Mode 769 xxxiv www.it-ebooks.infoftoc.indd xxxiv 4/11/2012 10:34:50 AM
  • 37. Meier02275 ftoc V2 - 03/22/2012 CONTENTS CHAPTER 19: MONETIZING, PROMOTING, AND DISTRIBUTING APPLICATIONS 771 Signing and Publishing Applications 772 Signing Applications Using the Export Android Application Wizard 772 Distributing Applications 774 Introducing the Google Play 774 Getting Started with Google Play 775 Publishing Applications 776 Application Reports Within the Developer Console 778 Accessing Application Error Reports 778 An Introduction to Monetizing Your Applications 779 Application Marketing, Promotion, and Distribution Strategies 780 Application Launch Strategies 781 Promotion Within Google Play 781 Internationalization 782 Analytics and Referral Tracking 783 Using Google Analytics for Mobile Applications 784 Referral Tracking with Google Analytics 786 INDEX 787 xxxv www.it-ebooks.infoftoc.indd xxxv 4/11/2012 10:34:50 AM
  • 38. Meier02275 flast V3 - 03/25/2012 www.it-ebooks.infoflast.indd xxxvi 4/11/2012 10:37:32 AM
  • 39. Meier02275 flast V3 - 03/25/2012 INTRODUCTION THIS IS AN EXCITING TIME FOR ANDROID DEVELOPERS. Mobile phones have never been more popu- lar; powerful smartphones are now a regular choice for consumers; and the Android ecosystem has expanded to include tablet and TV devices to further expand the audience of your Android applications. Hundreds of stylish and versatile devices — packing hardware features such as GPS, accelerometers, NFC, and touch screens, combined with reasonably priced data plans — provide an enticing plat- form upon which to create innovative applications for all Android devices. Android offers an open alternative for mobile application development. Without artificial barriers, Android developers are free to write applications that take full advantage of increasingly powerful mobile hardware and distribute them in an open market. As a result, developer interest in Android devices has exploded as handset sales have continued to grow. As of 2012, there are hundreds of handset and tablet OEMs, including HTC, Motorola, LG, Samsung, ASUS, and Sony Ericsson. More than 300 million Android devices have been activated, and that number is growing at a rate of over 850,000 activations every day. Using Google Play for distribution, developers can take advantage of an open marketplace, with no review process, for distributing free and paid applications to all compatible Android devices. Built on an open-source framework, and featuring powerful SDK libraries, Android has enabled more than 450,000 applications to be launched in Google Play. This book is a hands-on guide to building mobile applications using version 4 of the Android SDK. Chapter by chapter, it takes you through a series of sample projects, each introducing new features and techniques to get the most out of Android. It covers all the basic functionality to get started, as well as the information for experienced mobile developers to leverage the unique features of Android to enhance existing products or create innovative new ones. Google’s philosophy is to release early and iterate often. Since Android’s fi rst full release in December 2008, there have been 19 platform and SDK releases. With such a rapid release cycle, there are likely to be regular changes and improvements to the software and devel