Reto currently works as a Developer Advocate on the Android team at Google, helping Android developers create the best applications possible.. INTRODUCTION xxxvii Android: An Open Platfo
Trang 3ANDROID™ 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
Trang 5PROFESSIONAL
Android ™ 4 Application Development
Trang 7PROFESSIONAL
Android ™ 4 Application Development
Reto Meier
Trang 8Professional Android™ 4 Application Development
Copyright © 2012 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
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.
Trang 9To Kris
Trang 11ABOUT 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
Trang 13ABOUT 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
Trang 15Mary Beth Wakefi eld
FREELANCER EDITORIAL MANAGER
Trang 17FIRST, 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
Trang 19INTRODUCTION xxxvii
Android: An Open Platform for Mobile Development 4
Using Widgets and Live Wallpaper to Enhance the Home Screen 9
Trang 20Developing for Mobile and Embedded Devices 38
Trang 21Introducing the Application Manifest File 55
Creating Resources for Diff erent Languages and Hardware 77
Understanding an Application’s Priority and Its Process’ States 82 Introducing the Android Application Class 83
Trang 22Using Layouts to Create Device Independent User Interfaces 100
Trang 23Creating Intent Filters and Broadcast Receivers 183
Finding and Using Intents Received Within an Activity 186
Discovering New Actions from Third-Party Intent Receivers 194
Trang 24Monitoring Device State Changes Using Broadcast Intents 197
Downloading and Parsing Internet Resources 201
Best Practices for Downloading Data Without Draining
Creating a Settings Activity for the Earthquake Viewer 223 Introducing the Preference Framework and the
Using Intents to Import System Preferences into Preference Screens 234
Defi ning the Preference Fragment Hierarchy
Finding and Using the Shared Preferences Set by Preference Screens 238
Trang 25Creating a Standard Preference Activity for the Earthquake Viewer 238 Persisting the Application Instance State 242
Saving and Restoring Activity Instance State
Saving and Restoring Fragment Instance State
Opening and Creating Databases Without the SQLite Open Helper 257
Trang 26Querying for Content Asynchronously Using the Cursor Loader 277
Making Your Search Activity the Default Search Provider
Creating a Searchable Earthquake Content Provider 301
Trang 27Executing a Service and Controlling Its Restart Behavior 333
Using the Intent Service to Simplify the Earthquake
Customizing the Action Bar to Control Application Navigation Behavior 364
Adding an Action Bar to the Earthquake Monitor 370 Creating and Using Menus and Action Bar Action Items 377
Trang 28Managing and Displaying Dialogs Using Activity Event Handlers 400
Creating a Notifi cation and Confi guring the Status Bar Display 407Using the Default Notifi cation Sounds, Lights, and Vibrations 408
Adding Notifi cations and Dialogs to the Earthquake Monitor 418
Designing for Every Screen Size and Density 426
Trang 29xxvii
Trang 30Managing Hardware Acceleration Use in Your Applications 466
Monitoring a Device’s Movement and Orientation 489
Calculating Orientation Using the Accelerometer and
Determining Orientation Using the Deprecated Orientation Sensor 501
Trang 31CHAPTER 13: MAPS, GEOCODING, AND
Using the Emulator with Location-Based Services 515
Confi guring the Emulator to Test Location-Based Services 516
Trang 32Creating Your Widget Intent Receiver and Adding It to the
Populating Collection View Widgets Using a Remote Views Service 594Adding Interactivity to the Items Within a Collection View Widget 595
Trang 33Surfacing Application Search Results Using the Quick Search Box 614
Adding the Earthquake Example Search Results to the
Controlling Auto Focus, Focus Areas, and Metering Areas 650
Trang 34Selecting Remote Bluetooth Devices for Communications 675
Managing Network and Internet Connectivity 679
Supporting User Preferences for Background Data Transfers 679
Trang 35Monitoring Changes in Phone State Using the Phone State Listener 708
Monitoring Data Connectivity and Data Transfer Status Changes 711
Sending SMS and MMS from Your Application Using Intents 713
Trang 36Implementing Copy Protection Using the License
Finding Your Public Key and Defi ning Your Purchasable Items 754
Using AIDL to Support Inter-Process Communication for Services 759
Implementing and Exposing the AIDL Service Defi nition 762
Dealing with Diff erent Hardware and Software Availability 765
Optimizing UI Performance with Strict Mode 769
Trang 37CHAPTER 19: MONETIZING, PROMOTING, AND DISTRIBUTING
APPLICATIONS 771
Signing Applications Using the Export Android Application Wizard 772
An Introduction to Monetizing Your Applications 779 Application Marketing, Promotion, and Distribution Strategies 780
Internationalization 782
INDEX 787
Trang 39THIS IS AN EXCITING TIME FOR ANDROID DEVELOPERS Mobile phones have never been more 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
popu-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 artifi cial 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 development libraries While the Android engineering team works hard to ensure backward compatibility, future releases are likely to date some of the information provided in this book Similarly, not all active Android devices will be running the latest platform release
Wherever possible, I have included details on which platform releases support the functionality described, and which alternatives may exist to provide support for users of older devices Further, the explanations and examples included will give you the grounding and knowledge needed to write compelling mobile applications using the current SDK, along with the fl exibility to quickly adapt to future enhancements
Trang 40WHO THIS BOOK IS FOR
This book is for anyone interested in creating applications for the Android platform It includes
information that will be valuable, whether you’re an experienced mobile developer or making your
fi rst foray, via Android, into writing mobile applications
It will help if you have used smartphones (particularly phones running Android), but it’s not
neces-sary, nor is prior experience in mobile application development
It’s expected that you’ll have some experience in software development and be familiar with basic
object-oriented development practices An understanding of Java syntax is a requirement, and
detailed knowledge and experience is a distinct advantage, though not a strict necessity
Chapters 1 and 2 introduce mobile development and contain instructions to get you started in
Android Beyond that, there’s no requirement to read the chapters in order, although a good
under-standing of the core components described in Chapters 3–9 is important before you venture into
the remaining chapters Chapters 10 and 11 cover important details on how to create an application
that provides a rich and consistent user experience, while Chapters 12–19 cover a variety of optional
and advanced functionality and can be read in whatever order interest or need dictates
WHAT THIS BOOK COVERS
Chapter 1 introduces Android, including what it is and how it fi ts into existing mobile development
What Android offers as a development platform and why it’s an exciting opportunity for creating
mobile phone applications are then examined in greater detail
Chapter 2 covers some best practices for mobile development and explains how to download the
Android SDK and start developing applications It also introduces the Android Developer Tools and
demonstrates how to create new applications from scratch
Chapters 3–9 take an in-depth look at the fundamental Android application components Starting
with examining the pieces that make up an Android application and its lifecycle, you’ll quickly move
on to the application manifest and external resources before learning about “Activities,” their
life-times, and their lifecycles
You’ll then learn how to create basic user interfaces with layouts, Views, and Fragments, before being
introduced to the Intent and Broadcast Receiver mechanisms used to perform actions and send
mes-sages between application components Internet resources are then covered, followed by a detailed
look at data storage, retrieval, and sharing You’ll start with the preference-saving mechanism and
then move on to fi le handling, databases, and Cursors You’ll also learn how share application data
using Content Providers and access data from the native Content Providers This section fi nishes with
an examination of how to work in the background using Services and background Threads
Chapters 10 and 11 build on the UI lessons you learned in Chapter 4, examining how to enhance
the user experience through the use of the Action Bar, Menu System, and Notifi cations You’ll
learn how to make your applications display-agnostic (optimized for a variety of screen sizes and