the android developer's collection

212

Upload: others

Post on 11-Sep-2021

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Android Developer's Collection
Page 2: The Android Developer's Collection

The AndroidDeveloper’sCollection

Upper Saddle River, NJ • Boston • Indianapolis • San FranciscoNew York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

Page 3: The Android Developer's Collection

Note from the PublisherThe Android Developer’s Collection includes two highly successful Android applicationdevelopment eBooks:

• The Android Developer’s Cookbook: Building Applications with the Android SDK

• Android Wireless Application Development, Second Edition

The Android Developer’s Cookbook contains many invaluable “recipes” that working devel-opers will want to use in their production-level code. Android Wireless ApplicationDevelopment is an excellent way for experienced developers to come up-to-speed quicklyon the ins and outs of Android application development.

To simplify access, we’ve appended “A” to pages of The Android Developer’s Cookbook and“B” to pages of Android Wireless Application Development.This enabled us to produce a sin-gle, comprehensive table of contents and dedicated indexes so that you can easily link tothe topics you want.We hope you find this collection useful!

—The editorial and production teams at Addison-Wesley Professional

Page 4: The Android Developer's Collection

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks.Where those designations appear in this book, and the pub-lisher was aware of a trademark claim, the designations have been printed with initialcapital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors oromissions. No liability is assumed for incidental or consequential damages in connectionwith or arising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulkpurchases or special sales, which may include electronic versions and/or custom coversand content particular to your business, training goals, marketing focus, and brandinginterests. For more information, please contact:

U.S. Corporate and Government Sales(800) [email protected]

For sales outside the United States, please contact:

International [email protected]

Visit us on the Web: informit.com/aw

The Android Developer’s Cookbook copyright © 2012 Pearson Education, Inc.

Android Wireless Application Development copyright © 2012 Shane Conder and Lauren Darcey

All rights reserved. Printed in the United States of America.This publication is protectedby copyright, and permission must be obtained from the publisher prior to any prohibit-ed reproduction, storage in a retrieval system, or transmission in any form or by anymeans, electronic, mechanical, photocopying, recording, or likewise.To obtain permissionto use material from this work, please submit a written request to Pearson Education,Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458,or you may fax your request to (201) 236-3290.

ISBN-13: 978-0-13-292861-8ISBN-10: 0-13-292861-2

Page 5: The Android Developer's Collection

Table of Contents

THE ANDROID DEVELOPER’S COOKBOOK

1 Overview of Android . . . . . . . . . . . . . . . . . . . . .1AThe Evolution of Android . . . . . . . . . . . . . . . . . . . . .1A

The Dichotomy of Android . . . . . . . . . . . . . . . . . . . .2A

Devices Running Android . . . . . . . . . . . . . . . . . . . . .2A

HTC Models . . . . . . . . . . . . . . . . . . . . . . . . . . . .6A

Motorola Models . . . . . . . . . . . . . . . . . . . . . . . .6A

Samsung Models . . . . . . . . . . . . . . . . . . . . . . . .6A

Tablets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7A

Other Devices . . . . . . . . . . . . . . . . . . . . . . . . . .7A

Hardware Differences on Android Devices . . . . . . . .8A

Screens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8A

User Input Methods . . . . . . . . . . . . . . . . . . . . . .9A

Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9A

Features of Android . . . . . . . . . . . . . . . . . . . . . . .10A

Multiprocess and App Widgets . . . . . . . . . . . . .11A

Touch, Gestures, and Multitouch . . . . . . . . . . . .11A

Hard and Soft Keyboards . . . . . . . . . . . . . . . . .11A

Android Development . . . . . . . . . . . . . . . . . . . . . .11A

How to Use the Recipes in This Book . . . . . . . .12A

Designing Applications Well . . . . . . . . . . . . . . .12A

Maintaining Forward Compatibility . . . . . . . . . . .13A

Robustness . . . . . . . . . . . . . . . . . . . . . . . . . . .13A

Software Development Kit . . . . . . . . . . . . . . . . . . .14A

Installing and Upgrading . . . . . . . . . . . . . . . . . .14A

Software Features and API Level . . . . . . . . . . . .15A

Emulator and Android Device Debug . . . . . . . . .16A

Using the Android Debug Bridge . . . . . . . . . . . .18A

Signing and Publishing . . . . . . . . . . . . . . . . . . .18A

Android Market . . . . . . . . . . . . . . . . . . . . . . . . . . .19A

End-User License Agreement . . . . . . . . . . . . . . .19A

Improving App Visibility . . . . . . . . . . . . . . . . . . .19A

Differentiating an App . . . . . . . . . . . . . . . . . . . .20A

Charging for an App . . . . . . . . . . . . . . . . . . . . .20A

Page 6: The Android Developer's Collection

Managing Reviews and Updates . . . . . . . . . . . .21A

Alternatives to the Android Market . . . . . . . . . .22A

2 Application Basics: Activities and Intents . . . .23AAndroid Application Overview . . . . . . . . . . . . . . . . .23A

Recipe: Creating a Project and an Activity . . . . .24A

Directory Structure of Project and Autogenerated Content . . . . . . . . . . . . . . . . . .26A

Android Package and Manifest File . . . . . . . . . .28A

Renaming Parts of an Application . . . . . . . . . . .30A

Activity Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . .30A

Recipe: Utilizing Other Lifecycle Functions . . . . .31A

Recipe: Forcing Single Task Mode . . . . . . . . . . .33A

Recipe: Forcing Screen Orientation . . . . . . . . . .34A

Recipe: Saving and Restoring Activity Information . . . . . . . . . . . . . . . . . . . . . . . . . .34A

Multiple Activities . . . . . . . . . . . . . . . . . . . . . . . . .35A

Recipe: Using Buttons and TextView . . . . . . . . .36A

Recipe: Launching Another Activity from an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37A

Recipe: Launching an Activity for a Result Using Speech to Text . . . . . . . . . . . . . . . . . . .41A

Recipe: Implementing a List of Choices . . . . . . .43A

Recipe: Using Implicit Intents for Creating an Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44A

Recipe: Passing Primitive Data Types Between Activities . . . . . . . . . . . . . . . . . . . . .46A

3 Threads, Services, Receivers, and Alerts . . . . .51AThreads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51A

Recipe: Launching a Secondary Thread . . . . . . .51A

Recipe: Creating a Runnable Activity . . . . . . . . .55A

Recipe: Setting a Thread’s Priority . . . . . . . . . . .57A

Recipe: Canceling a Thread . . . . . . . . . . . . . . .57A

Recipe: Sharing a Thread Between Two Applications . . . . . . . . . . . . . . . . . . . . . . . . . .58A

Messages Between Threads: Handlers . . . . . . . . .58A

Recipe: Scheduling a Runnable Task from the Main Thread . . . . . . . . . . . . . . . . . . . . . . . . .59A

Page 7: The Android Developer's Collection

vi Contents

Recipe: Using a Countdown Timer . . . . . . . . . . .61A

Recipe: Handling a Time-Consuming Initialization . . . . . . . . . . . . . . . . . . . . . . . . . .62A

Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64A

Recipe: Creating a Self-Contained Service . . . . .65A

Adding a Broadcast Receiver . . . . . . . . . . . . . . . . .69A

Recipe: Starting a Service When the Camera Button Is Pressed . . . . . . . . . . . . . . . . . . . . .70A

App Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72A

Recipe: Creating an App Widget . . . . . . . . . . . .72A

Alerts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74A

Recipe: Using Toast to Show a Brief Message on the Screen . . . . . . . . . . . . . . . . . . . . . . . .74A

Recipe: Using an Alert Dialog Box . . . . . . . . . . .75A

Recipe: Showing Notification in Status Bar . . . .76A

4 User Interface Layout . . . . . . . . . . . . . . . . . . .79AResource Directories and General Attributes . . . . .79A

Recipe: Specifying Alternate Resources . . . . . . .81A

Views and ViewGroups . . . . . . . . . . . . . . . . . . . . .82A

Recipe: Building Layouts in the Eclipse Editor . .83A

Recipe: Controlling the Width and Height of UI Elements . . . . . . . . . . . . . . . . . . . . . . . . . .86A

Recipe: Setting Relative Layout and Layout ID . .89A

Recipe: Declaring a Layout Programmatically . . .90A

Recipe: Updating a Layout from a Separate Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . .92A

Text Manipulation . . . . . . . . . . . . . . . . . . . . . . . . .94A

Recipe: Setting and Changing Text Attributes . . .95A

Recipe: Providing Text Entry . . . . . . . . . . . . . . .98A

Recipe: Creating a Form . . . . . . . . . . . . . . . . .100A

Other Widgets: From Buttons to Seek Bars . . . . .101A

Recipe: Using Image Buttons in a Table Layout . . . . . . . . . . . . . . . . . . . . . . . .102A

Recipe: Using Check Boxes and Toggle Buttons . . . . . . . . . . . . . . . . . . . . . . .105A

Recipe: Using Radio Buttons . . . . . . . . . . . . . .108A

Recipe: Creating a Drop-Down Menu . . . . . . . .110A

Recipe: Using a Progress Bar . . . . . . . . . . . . .112A

Recipe: Using a SeekBar . . . . . . . . . . . . . . . .114A

Page 8: The Android Developer's Collection

viiContents

5 User Interface Events . . . . . . . . . . . . . . . . . .117AEvent Handlers and Event Listeners . . . . . . . . . . .117A

Recipe: Intercepting a Physical Key Press . . . .117A

Recipe: Building Menus . . . . . . . . . . . . . . . . .121A

Recipe: Defining Menus in XML . . . . . . . . . . . .126A

Recipe: Utilizing the SEARCH Key . . . . . . . . . .127A

Recipe: Reacting to Touch Events . . . . . . . . . .128A

Recipe: Listening for Fling Gestures . . . . . . . .130A

Recipe: Using Multitouch . . . . . . . . . . . . . . . .133A

Advanced User Interface Libraries . . . . . . . . . . . .136A

Recipe: Using Gestures . . . . . . . . . . . . . . . . .136A

Recipe: Drawing 3D Images . . . . . . . . . . . . . .140A

6 Multimedia Techniques . . . . . . . . . . . . . . . . .147AImages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .148A

Recipe: Loading an Image for Manipulation . . .148A

Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .154A

Recipe: Choosing and Playing Back Audio Files . . . . . . . . . . . . . . . . . . . . . . . . .154A

Recipe: Recording Audio Files . . . . . . . . . . . . .157A

Recipe: Manipulating Raw Audio . . . . . . . . . . .158A

Recipe: Using Sound Resources Efficiently . . .163A

Recipe: Adding Media and Updating Paths . . . .165A

Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .165A

7 Hardware Interface . . . . . . . . . . . . . . . . . . . .169ACamera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .169A

Recipe: Customizing the Camera . . . . . . . . . . .170A

Other Sensors . . . . . . . . . . . . . . . . . . . . . . . . . .175A

Recipe: Getting a Device’s Rotational Attitude .176A

Recipe: Using the Temperature and Light Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . .179A

Telephony . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180A

Recipe: Utilizing the Telephony Manager . . . . .181A

Recipe: Listening for Phone States . . . . . . . . .183A

Recipe: Dialing a Phone Number . . . . . . . . . . .185A

Bluetooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185A

Recipe: Turning on Bluetooth . . . . . . . . . . . . .186A

Page 9: The Android Developer's Collection

viii Contents

Recipe: Discovering Bluetooth Devices . . . . . .187A

Recipe: Pairing with Bonded Bluetooth Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . .188A

Recipe: Opening a Bluetooth Socket . . . . . . . .188A

Recipe: Using Device Vibration . . . . . . . . . . . .191A

Recipe: Accessing the Wireless Network . . . . .191A

8 Networking . . . . . . . . . . . . . . . . . . . . . . . . . .195AUsing SMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195A

Recipe: Autosend an SMS Based on a Received SMS . . . . . . . . . . . . . . . . . . . . . . .197A

Using Web Content . . . . . . . . . . . . . . . . . . . . . . .204A

Recipe: Customizing a Web Browser . . . . . . . .204A

Recipe: Using an HTTP GET . . . . . . . . . . . . . .204A

Recipe: Using HTTP POST . . . . . . . . . . . . . . . .209A

Social Networking . . . . . . . . . . . . . . . . . . . . . . . .210A

Recipe: Integrating with Twitter . . . . . . . . . . . .210A

9 Data Storage Methods . . . . . . . . . . . . . . . . .221AShared Preferences . . . . . . . . . . . . . . . . . . . . . .221A

Recipe: Creating and Retrieving Shared Preferences . . . . . . . . . . . . . . . . . . . . . . . . .222A

Recipe: Using the Preferences Framework . . . .222A

Recipe: Changing the UI Based on Stored Data . . . . . . . . . . . . . . . . . . . . . . . . .225A

Recipe: Adding a EULA . . . . . . . . . . . . . . . . . .228A

SQLite Database . . . . . . . . . . . . . . . . . . . . . . . .232A

Recipe: Creating a Separate Database Package . . . . . . . . . . . . . . . . . . . . . . . . . . .232A

Recipe: Using a Separate Database Package . . . . . . . . . . . . . . . . . . . . . . . . . . .236A

Recipe: Creating a Personal Diary . . . . . . . . . .239A

Content Provider . . . . . . . . . . . . . . . . . . . . . . . . .243A

Recipe: Creating a Custom Content Provider . .244A

File Saving and Loading . . . . . . . . . . . . . . . . . . .249A

10 Location-Based Services . . . . . . . . . . . . . . . .251ALocation Basics . . . . . . . . . . . . . . . . . . . . . . . . .251A

Recipe: Retrieving Last Location . . . . . . . . . . .253A

Page 10: The Android Developer's Collection

ixContents

Recipe: Updating Location Upon Change . . . . .254A

Recipe: Listing All Enabled Providers . . . . . . . .256A

Recipe: Translating a Location to Address (Reverse Geocoding) . . . . . . . . . . . . . . . . . .258A

Recipe: Translating an Address to Location (Geocoding) . . . . . . . . . . . . . . . . . . . . . . . . .261A

Using Google Maps . . . . . . . . . . . . . . . . . . . . . .263A

Recipe: Adding Google Maps to an Application . . . . . . . . . . . . . . . . . . . . . . . . .265A

Recipe: Adding Markers on a Map . . . . . . . . . .267A

Recipe: Adding Views to a Map . . . . . . . . . . . .271A

Recipe: Marking the Device’s Current Location on a Map . . . . . . . . . . . . . . . . . . . .274A

Recipe: Setting up a Proximity Alert . . . . . . . . .274A

11 Advanced Android Development . . . . . . . . . . .277AAndroid Custom View . . . . . . . . . . . . . . . . . . . . .277A

Recipe: Customizing a Button . . . . . . . . . . . . .277A

Android Native Components . . . . . . . . . . . . . . . .283A

Recipe: Developing a Native Component . . . . .284A

Android Security . . . . . . . . . . . . . . . . . . . . . . . . .287A

Recipe: Declaring and Enforcing Permissions . .288A

Android Inter-Process Communication . . . . . . . . .288A

Recipe: Implementing a Remote Procedure Call . . . . . . . . . . . . . . . . . . . . . . .289A

Android Backup Manager . . . . . . . . . . . . . . . . . .294A

Recipe: Creating a Backup of Runtime Data . . .294A

Recipe: Backing Up Files to the Cloud . . . . . . .296A

Recipe: Triggering Backup and Restore . . . . . .296A

Android Animation . . . . . . . . . . . . . . . . . . . . . . .298A

Recipe: Creating an Animation . . . . . . . . . . . .299A

12 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . .303AEclipse Built-in Debug Tools . . . . . . . . . . . . . . . . .303A

Recipe: Specifying a Run Configuration . . . . . .303A

Recipe: Using the DDMS . . . . . . . . . . . . . . . .304A

Recipe: Debugging Through Breakpoints . . . . .306A

Android SDK Debug Tools . . . . . . . . . . . . . . . . . .307A

Recipe: Using the Android Debug Bridge . . . . .307A

Page 11: The Android Developer's Collection

x Contents

Recipe: Using LogCat . . . . . . . . . . . . . . . . . . .307A

Recipe: Using the Hierarchy Viewer . . . . . . . . .309A

Recipe: Using TraceView . . . . . . . . . . . . . . . . .311A

Android System Debug Tools . . . . . . . . . . . . . . . .313A

Recipe: Setting up GDB Debugging . . . . . . . . .315A

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .317A

ANDROID WIRELESS APPLICATION DEVELOPMENT

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1BWho Should Read This Book . . . . . . . . . . . . . . . . . .1B

Key Questions Answered in This Book . . . . . . . . . . .2B

How This Book Is Structured . . . . . . . . . . . . . . . . . .2B

An Overview of Changes in This Edition . . . . . . . . . .3B

Development Environment Used in This Book . . . . . .4B

Supplementary Materials Available . . . . . . . . . . . . .5B

Where to Find More Information . . . . . . . . . . . . . . .5B

Conventions Used in This Book . . . . . . . . . . . . . . . .6B

Contacting the Authors . . . . . . . . . . . . . . . . . . . . . .6B

I: An Overview of Android

1 Introducing Android . . . . . . . . . . . . . . . . . . . . . .7BA Brief History of Mobile Software Development . . . .7B

Way Back When . . . . . . . . . . . . . . . . . . . . . . . . .7B

“The Brick” . . . . . . . . . . . . . . . . . . . . . . . . . . . .9B

Wireless Application Protocol (WAP) . . . . . . . . .11B

Proprietary Mobile Platforms . . . . . . . . . . . . . . .13B

The Open Handset Alliance . . . . . . . . . . . . . . . . . .15B

Google Goes Wireless . . . . . . . . . . . . . . . . . . .15B

Forming the Open Handset Alliance . . . . . . . . . .15B

Manufacturers: Designing the Android Handsets . . . . . . . . . . . . . . . . . . . . . . . . . . .16B

Mobile Operators: Delivering the Android Experience . . . . . . . . . . . . . . . . . . . . . . . . . .17B

Content Providers: Developing Android Applications . . . . . . . . . . . . . . . . . . . . . . . . .17B

Page 12: The Android Developer's Collection

xiContents

Taking Advantage of All Android Has to Offer . . .18B

Android Platform Differences . . . . . . . . . . . . . . . . .18B

Android: A Next-Generation Platform . . . . . . . . .18B

Free and Open Source . . . . . . . . . . . . . . . . . . .20B

Familiar and Inexpensive Development Tools . . .20B

Reasonable Learning Curve for Developers . . . .20B

Enabling Development of Powerful Applications .21B

Rich, Secure Application Integration . . . . . . . . .21B

No Costly Obstacles to Publication . . . . . . . . . .21B

A “Free Market” for Applications . . . . . . . . . . . .22B

A New and Growing Platform . . . . . . . . . . . . . . .22B

The Android Platform . . . . . . . . . . . . . . . . . . . . . .23B

Android’s Underlying Architecture . . . . . . . . . . .23B

Security and Permissions . . . . . . . . . . . . . . . . .25B

Developing Android Applications . . . . . . . . . . . .26B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28B

References and More Information . . . . . . . . . . . . .28B

2 Setting Up Your Android Development Environment . . . . . . . . . . . . . . . . . . . . . . . . .29B

Configuring Your Development Environment . . . . . .29B

Configuring Your Operating System for DeviceDebugging . . . . . . . . . . . . . . . . . . . . . . . . . . . .30B

Configuring Your Android Hardware for Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . .30B

Upgrading the Android SDK . . . . . . . . . . . . . . .31B

Problems with the Android Software Development Kit . . . . . . . . . . . . . . . . . . . . . .32B

Exploring the Android SDK . . . . . . . . . . . . . . . . . .32B

Understanding the Android SDK License Agreement . . . . . . . . . . . . . . . . . . . . . . . . . .32B

Reading the Android SDK Documentation . . . . .33B

Exploring the Android Application Framework . . .35B

Getting to Know the Android Tools . . . . . . . . . . .35B

Exploring the Android Sample Applications . . . . .40B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41B

References and More Information . . . . . . . . . . . . .41B

Page 13: The Android Developer's Collection

xii Contents

3 Writing Your First Android Application . . . . . . .43BTesting Your Development Environment . . . . . . . . .43B

Adding the Snake Application to a Project in Your Eclipse Workspace . . . . . . . . . . . . . . . . .43B

Creating an Android Virtual Device (AVD) for Your Snake Project . . . . . . . . . . . . . . . . . .44B

Creating a Launch Configuration for Your Snake Project . . . . . . . . . . . . . . . . . . . . . . . .46B

Running the Snake Application in the Android Emulator . . . . . . . . . . . . . . . . . . . . . .47B

Building Your First Android Application . . . . . . . . . .48B

Creating and Configuring a New Android Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50B

Core Files and Directories of the Android Application . . . . . . . . . . . . . . . . .50B

Creating an AVD for Your Project . . . . . . . . . . . .51B

Creating Launch Configurations for Your Project . . . . . . . . . . . . . . . . . . . . . . . . . .52B

Running Your Android Application in the Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . . .53B

Debugging Your Android Application in the Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . . .56B

Adding Logging Support to Your Android Application . . . . . . . . . . . . . . . . . . . . . . . . . .59B

Adding Some Media Support to Your Application . . . . . . . . . . . . . . . . . . . . . . . . . .60B

Adding Location-Based Services to Your Application . . . . . . . . . . . . . . . . . . . . . . . . . .62B

Debugging Your Application on the Hardware . . .65B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66B

References and More Information . . . . . . . . . . . . .67B

II: Android Application Design Essentials

4 Understanding the Anatomy of an Android Application . . . . . . . . . . . . . . . . . . . . . . . . . .69B

Mastering Important Android Terminology . . . . . . . .69B

Using the Application Context . . . . . . . . . . . . . .70B

Retrieving the Application Context . . . . . . . . .70B

Using the Application Context . . . . . . . . . . . .70B

Page 14: The Android Developer's Collection

xiiiContents

Performing Application Tasks with Activities . . . . . .71B

The Lifecycle of an Android Activity . . . . . . .72B

Managing Activity Transitions with Intents . . . . .76B

Working with Services . . . . . . . . . . . . . . . . . . . . . .78B

Receiving and Broadcasting Intents . . . . . . . . . . . .79B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .80B

References and More Information . . . . . . . . . . . . .80B

5 Defining Your Application Using the Android Manifest File . . . . . . . . . . . . . . . . . . . . . . . .81B

Configuring the Android Manifest File . . . . . . . . . . .81B

Editing the Android Manifest File . . . . . . . . . . . .82B

Managing Your Application’s Identity . . . . . . . . . . .86B

Versioning Your Application . . . . . . . . . . . . . . . .86B

Setting the Application Name and Icon . . . . . . .87B

Enforcing Application System Requirements . . . . . .87B

Targeting Specific SDK Versions . . . . . . . . . . . .87B

Enforcing Application Platform Requirements . . .90B

Working with External Libraries . . . . . . . . . . . . .92B

Registering Activities and Other Application Components . . . . . . . . . . . . . . . . . . . . . . . . . . .92B

Designating a Primary Entry Point Activity for Your Application Using an Intent Filter . . . . . . .92B

Configuring Other Intent Filters . . . . . . . . . . . . .93B

Working with Permissions . . . . . . . . . . . . . . . . . . .94B

Registering Permissions Your Application Requires . . . . . . . . . . . . . . . . . . . . . . . . . . . .94B

Registering Permissions Your Application Grants to Other Applications . . . . . . . . . . . . . .95B

Exploring Other Manifest File Settings . . . . . . . . . .96B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96B

References and More Information . . . . . . . . . . . . .96B

6 Managing Application Resources . . . . . . . . . . .97BWhat Are Resources? . . . . . . . . . . . . . . . . . . . . . .97B

Storing Application Resources . . . . . . . . . . . . .97B

Understanding the Resource Directory Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . .97B

Resource Value Types . . . . . . . . . . . . . . . . . . .99B

Page 15: The Android Developer's Collection

xiv Contents

Storing Different Resource Value Types . . . . . .101B

Accessing Resources Programmatically . . . . . .103B

Setting Simple Resource Values Using Eclipse . . .104B

Working with Resources . . . . . . . . . . . . . . . . . . .107B

Working with String Resources . . . . . . . . . .107B

Using String Resources as Format Strings . . . .108B

Working with String Arrays . . . . . . . . . . . . . . .109B

Working with Boolean Resources . . . . . . . . .110B

Working with Integer Resources . . . . . . . . .111B

Working with Colors . . . . . . . . . . . . . . . . . . . .111B

Working with Dimensions . . . . . . . . . . . . . . . .112B

Working with Simple Drawables . . . . . . . . . . . .113B

Working with Images . . . . . . . . . . . . . . . . . . .114B

Working with Animation . . . . . . . . . . . . . . . . .116B

Working with Menus . . . . . . . . . . . . . . . . . . . .119B

Working with XML Files . . . . . . . . . . . . . . . . . .120B

Working with Raw Files . . . . . . . . . . . . . . . . . .121B

References to Resources . . . . . . . . . . . . . . . .122B

Working with Layouts . . . . . . . . . . . . . . . . . . .123B

Working with Styles . . . . . . . . . . . . . . . . . . . .127B

Working with Themes . . . . . . . . . . . . . . . . . . .131B

Referencing System Resources . . . . . . . . . . . . . .131B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132B

References and More Information . . . . . . . . . . . .132B

III: Android User Interface Design Essentials

7 Exploring User Interface Screen Elements . . .133BIntroducing Android Views and Layouts . . . . . . . .133B

Introducing the Android View . . . . . . . . . . . . . .133B

Introducing the Android Control . . . . . . . . . . . .133B

Introducing the Android Layout . . . . . . . . . . . .134B

Displaying Text to Users with TextView . . . . . . .134B

Configuring Layout and Sizing . . . . . . . . . . . . .135B

Creating Contextual Links in Text . . . . . . . . . .136B

Retrieving Data from Users . . . . . . . . . . . . . . . . .137B

Retrieving Text Input Using EditTextControls . . . . . . . . . . . . . . . . . . . . . . . . . . .138B

Page 16: The Android Developer's Collection

xvContents

Giving Users Input Choices Using SpinnerControls . . . . . . . . . . . . . . . . . . . . . . . . . . .142B

Using Buttons, Check Boxes, and Radio Groups . .144B

Using Basic Buttons . . . . . . . . . . . . . . . . . . . .144B

Using Check Boxes and Toggle Buttons . . . . . .146B

Using RadioGroups and RadioButtons . .147B

Getting Dates and Times from Users . . . . . . . . . .150B

Using Indicators to Display Data to Users . . . . . .151B

Indicating Progress with ProgressBar . . . . .151B

Adjusting Progress with SeekBar . . . . . . . . . . . .153B

Displaying Rating Data with RatingBar . . . .154B

Showing Time Passage with the Chronometer . . . . . . . . . . . . . . . . . . . . . . . .155B

Displaying the Time . . . . . . . . . . . . . . . . . . . .156B

Providing Users with Options and Context Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .157B

Enabling the Options Menu . . . . . . . . . . . . . . .157B

Enabling the ContextMenu . . . . . . . . . . . . .159B

Handling User Events . . . . . . . . . . . . . . . . . . . . .161B

Listening for Touch Mode Changes . . . . . . . . .161B

Listening for Events on the Entire Screen . . . .162B

Listening for Long Clicks . . . . . . . . . . . . . . . .163B

Listening for Focus Changes . . . . . . . . . . . . . .164B

Working with Dialogs . . . . . . . . . . . . . . . . . . . . .165B

Exploring the Different Types of Dialogs . . . . . .165B

Tracing the Lifecycle of a Dialog . . . . . . . . . . .166B

Working with Custom Dialogs . . . . . . . . . . . . .168B

Working with Styles . . . . . . . . . . . . . . . . . . . . . .168B

Working with Themes . . . . . . . . . . . . . . . . . . . . .170B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171B

8 Designing User Interfaces with Layouts . . . . .173BCreating User Interfaces in Android . . . . . . . . . . .173B

Creating Layouts Using XML Resources . . . . . .173B

Creating Layouts Programmatically . . . . . . . . .175B

Organizing Your User Interface . . . . . . . . . . . . . . .177B

Understanding View versus ViewGroup . . . .178B

Using Built-In Layout Classes . . . . . . . . . . . . . . .181B

Page 17: The Android Developer's Collection

xvi Contents

Using FrameLayout . . . . . . . . . . . . . . . . . .183B

Using LinearLayout . . . . . . . . . . . . . . . . .185B

Using RelativeLayout . . . . . . . . . . . . . . .186B

Using TableLayout . . . . . . . . . . . . . . . . . .190B

Using Multiple Layouts on a Screen . . . . . . . .192B

Using Built-In View Container Classes . . . . . . . .192B

Using Data-Driven Containers . . . . . . . . . . . . .194B

Organizing Screens with Tabs . . . . . . . . . . . . .198B

Adding Scrolling Support . . . . . . . . . . . . . . . .201B

Exploring Other View Containers . . . . . . . . . . .202B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .203B

9 Drawing and Working with Animation . . . . . . .205BDrawing on the Screen . . . . . . . . . . . . . . . . . . . .205B

Working with Canvases and Paints . . . . . . . . .205B

Working with Text . . . . . . . . . . . . . . . . . . . . . . . .210B

Using Default Fonts and Typefaces . . . . . . . . .210B

Using Custom Typefaces . . . . . . . . . . . . . . . .211B

Measuring Text Screen Requirements . . . . . . .212B

Working with Bitmaps . . . . . . . . . . . . . . . . . . . . .212B

Drawing Bitmap Graphics on a Canvas . . . . . .213B

Scaling Bitmap Graphics . . . . . . . . . . . . . . . .213B

Transforming Bitmaps Using Matrixes . . . . . . .213B

Working with Shapes . . . . . . . . . . . . . . . . . . . . .214B

Defining Shape Drawables as XML Resources . . . . . . . . . . . . . . . . . . . . . .214B

Defining Shape Drawables Programmatically . .215B

Drawing Different Shapes . . . . . . . . . . . . . . . .215B

Working with Animation . . . . . . . . . . . . . . . . . . . .221B

Working with Frame-by-Frame Animation . . . . . .223B

Working with Tweened Animations . . . . . . . . . .224B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .230B

IV: Using Common Android APIs

10 Using Android Data and Storage APIs . . . . . .231BWorking with Application Preferences . . . . . . . . . .231B

Creating Private and Shared Preferences . . . . .232B

Page 18: The Android Developer's Collection

xviiContents

Searching and Reading Preferences . . . . . . . .232B

Adding, Updating, and Deleting Preferences . . .233B

Finding Preferences Data on the Android File System . . . . . . . . . . . . . . . . . . . . . . . . .234B

Working with Files and Directories . . . . . . . . . . . .235B

Exploring with the Android Application Directories . . . . . . . . . . . . . . . . . . . . . . . . .235B

Working with Other Directories and Files on the Android File System . . . . . . . . . . . . . . . .238B

Storing Structured Data Using SQLite Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . .239B

Creating a SQLite Database . . . . . . . . . . . . . .240B

Creating, Updating, and Deleting Database Records . . . . . . . . . . . . . . . . . . . . . . . . . . .242B

Querying SQLite Databases . . . . . . . . . . . . . .244B

Closing and Deleting a SQLite Database . . . . .250B

Designing Persistent Databases . . . . . . . . . . .250B

Binding Data to the Application User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . .253B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .257B

References and More Information . . . . . . . . . . . .258B

11 Sharing Data Between Applications with ContentProviders . . . . . . . . . . . . . . . . . . . . . . . . . . .259BExploring Android’s Content Providers . . . . . . . . .259B

Using the MediaStore Content Provider . . . .260B

Using the CallLog Content Provider . . . . . . .261B

Using the Browser Content Provider . . . . . . . .263B

Using the Contacts Content Provider . . . . . . . .264B

Using the UserDictionary ContentProvider . . . . . . . . . . . . . . . . . . . . . . . . . . .267B

Using the Settings Content Provider . . . . . .267B

Modifying Content Providers Data . . . . . . . . . . . .267B

Adding Records . . . . . . . . . . . . . . . . . . . . . . .267B

Updating Records . . . . . . . . . . . . . . . . . . . . .268B

Deleting Records . . . . . . . . . . . . . . . . . . . . . .269B

Enhancing Applications Using Content Providers . .269B

Accessing Images on the Device . . . . . . . . . . .270B

Acting as a Content Provider . . . . . . . . . . . . . . . .274B

Implementing a Content Provider Interface . . . .275B

Page 19: The Android Developer's Collection

xviii Contents

Defining the Data URI . . . . . . . . . . . . . . . . . .276B

Defining Data Columns . . . . . . . . . . . . . . . . . .276B

Implementing Important Content Provider Methods . . . . . . . . . . . . . . . . . . . . . . . . . . .276B

Updating the Manifest File . . . . . . . . . . . . . . .282B

Working with Live Folders . . . . . . . . . . . . . . . . . .282B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .285B

References and More Information . . . . . . . . . . . .285B

12 Using Android Networking APIs . . . . . . . . . . .287BUnderstanding Mobile Networking

Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . .287B

Accessing the Internet (HTTP) . . . . . . . . . . . . . . .288B

Reading Data from the Web . . . . . . . . . . . . . .288B

Using HttpURLConnection . . . . . . . . . . . .289B

Parsing XML from the Network . . . . . . . . . . . .290B

Processing Asynchronously . . . . . . . . . . . . . . .291B

Working with AsyncTask . . . . . . . . . . . . . . .292B

Using Threads for Network Calls . . . . . . . . . . .293B

Displaying Images from a Network Resource . .295B

Retrieving Android Network Status . . . . . . . . .297B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .298B

References and More Information . . . . . . . . . . . .299B

13 Using Android Web APIs . . . . . . . . . . . . . . . .301BBrowsing the Web with WebView . . . . . . . . . . . .301B

Designing a Layout with a WebView Control . .302B

Loading Content into a WebView Control . . . .302B

Adding Features to the WebView Control . . . .304B

Building Web Extensions Using WebKit . . . . . . . .307B

Browsing the WebKit APIs . . . . . . . . . . . . . . . .307B

Extending Web Application Functionality to Android . . . . . . . . . . . . . . . . . . . . . . . . . . . .308B

Working with Flash . . . . . . . . . . . . . . . . . . . . . . .311B

Enabling Flash Applications . . . . . . . . . . . . . .312B

Building AIR Applications for Android . . . . . . . .313B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .314B

References and More Information . . . . . . . . . . . .314B

Page 20: The Android Developer's Collection

xixContents

14 Using Location-Based Services (LBS) APIs . .315BUsing Global Positioning Services (GPS) . . . . . . .315B

Using GPS Features in Your Applications . . . . .316B

Finding Your Location . . . . . . . . . . . . . . . . . . .316B

Locating Your Emulator . . . . . . . . . . . . . . . . . .318B

Geocoding Locations . . . . . . . . . . . . . . . . . . . . .318B

Mapping Locations . . . . . . . . . . . . . . . . . . . . . . .322B

Mapping Intents . . . . . . . . . . . . . . . . . . . . . . .322B

Mapping Views . . . . . . . . . . . . . . . . . . . . . . .322B

Getting Your Debug API Key . . . . . . . . . . . . . .325B

Panning the Map View . . . . . . . . . . . . . . . . . .326B

Zooming the Map View . . . . . . . . . . . . . . . . . .327B

Marking the Spot . . . . . . . . . . . . . . . . . . . . . .327B

Doing More with Location-Based Services . . . . . .332B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .333B

References and More Information . . . . . . . . . . . .333B

15 Using Android Multimedia APIs . . . . . . . . . . .335BWorking with Multimedia . . . . . . . . . . . . . . . . . . .335B

Working with Still Images . . . . . . . . . . . . . . . . . .336B

Capturing Still Images Using the Camera . . . . .336B

Configuring Camera Mode Settings . . . . . . . . .340B

Sharing Images . . . . . . . . . . . . . . . . . . . . . . .341B

Assigning Images as Wallpapers . . . . . . . . . . .342B

Working with Video . . . . . . . . . . . . . . . . . . . . . . .343B

Recording Video . . . . . . . . . . . . . . . . . . . . . . .343B

Playing Video . . . . . . . . . . . . . . . . . . . . . . . . .345B

Working with Audio . . . . . . . . . . . . . . . . . . . . . . .346B

Recording Audio . . . . . . . . . . . . . . . . . . . . . . .347B

Playing Audio . . . . . . . . . . . . . . . . . . . . . . . . .348B

Sharing Audio . . . . . . . . . . . . . . . . . . . . . . . .349B

Searching for Multimedia . . . . . . . . . . . . . . . .350B

Working with Ringtones . . . . . . . . . . . . . . . . .351B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .351B

References and More Information . . . . . . . . . . . .351B

Page 21: The Android Developer's Collection

xx Contents

16 Using Android Telephony APIs . . . . . . . . . . . .353BWorking with Telephony Utilities . . . . . . . . . . . . . .353B

Gaining Permission to Access Phone State Information . . . . . . . . . . . . . . . . . . . . . . . . .354B

Requesting Call State . . . . . . . . . . . . . . . . . .354B

Requesting Service Information . . . . . . . . . . .356B

Monitoring Signal Strength and Data Connection Speed . . . . . . . . . . . . . . . . . . . .356B

Working with Phone Numbers . . . . . . . . . . . . .357B

Using SMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . .357B

Gaining Permission to Send and Receive SMS Messages . . . . . . . . . . . . . . . . . . . . . .358B

Sending an SMS . . . . . . . . . . . . . . . . . . . . . .358B

Receiving an SMS . . . . . . . . . . . . . . . . . . . . .360B

Making and Receiving Phone Calls . . . . . . . . . . .362B

Making Phone Calls . . . . . . . . . . . . . . . . . . . .362B

Receiving Phone Calls . . . . . . . . . . . . . . . . . .364B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .365B

References and More Information . . . . . . . . . . . .365B

17 Using Android 3D Graphics with OpenGL ES . .367BWorking with OpenGL ES . . . . . . . . . . . . . . . . . . .367B

Leveraging OpenGL ES in Android . . . . . . . . . .368B

Ensuring Device Compatibility . . . . . . . . . . . . .368B

Using OpenGL ES APIs in the Android SDK . . . . . .369B

Handling OpenGL ES Tasks Manually . . . . . . . . . .369B

Creating a SurfaceView . . . . . . . . . . . . . . .370B

Starting Your OpenGL ES Thread . . . . . . . . . . .371B

Initializing EGL . . . . . . . . . . . . . . . . . . . . . . . .373B

Initializing GL . . . . . . . . . . . . . . . . . . . . . . . . .374B

Drawing on the Screen . . . . . . . . . . . . . . . . . .375B

Drawing 3D Objects . . . . . . . . . . . . . . . . . . . . . .376B

Drawing Your Vertices . . . . . . . . . . . . . . . . . . .376B

Coloring Your Vertices . . . . . . . . . . . . . . . . . .377B

Drawing More Complex Objects . . . . . . . . . . . .378B

Lighting Your Scene . . . . . . . . . . . . . . . . . . . .379B

Texturing Your Objects . . . . . . . . . . . . . . . . . .381B

Interacting with Android Views and Events . . . . . .383B

Page 22: The Android Developer's Collection

xxiContents

Enabling the OpenGL Thread to Talk to the Application Thread . . . . . . . . . . . . . . . . . . . .384B

Enabling the Application Thread to Talk to the OpenGL Thread . . . . . . . . . . . . . . . . . . . . . .386B

Cleaning Up OpenGL ES . . . . . . . . . . . . . . . . . . .387B

Using GLSurfaceView (Easy OpenGL ES) . . . . . . .388B

Using OpenGL ES 2.0 . . . . . . . . . . . . . . . . . . . . .391B

Configuring Your Application for OpenGL ES 2.0 . . . . . . . . . . . . . . . . . . . . . .391B

Requesting an OpenGL ES 2.0 Surface . . . . . .391B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .395B

References and More Information . . . . . . . . . . . .396B

18 Using the Android NDK . . . . . . . . . . . . . . . . .397BDetermining When to Use the Android NDK . . . . .397B

Installing the Android NDK . . . . . . . . . . . . . . . . .398B

Exploring the Android NDK . . . . . . . . . . . . . . . . .398B

Running an Android NDK Sample Application . .399B

Creating Your Own NDK Project . . . . . . . . . . . . . .399B

Calling Native Code from Java . . . . . . . . . . . . .400B

Handling Parameters and Return Values . . . . .401B

Using Exceptions with Native Code . . . . . . . . .402B

Improving Graphics Performance . . . . . . . . . . . . .403B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405B

References and More Information . . . . . . . . . . . .405B

19 Using Android’s Optional Hardware APIs . . . .407BInteracting with Device Hardware . . . . . . . . . . . . .407B

Using the Device Sensor . . . . . . . . . . . . . . . . . . .408B

Working with Different Sensors . . . . . . . . . . . .408B

Acquiring Access to a Sensor . . . . . . . . . . . . .409B

Reading Sensor Data . . . . . . . . . . . . . . . . . . .409B

Calibrating Sensors . . . . . . . . . . . . . . . . . . . .410B

Determining Device Orientation . . . . . . . . . . . .411B

Finding True North . . . . . . . . . . . . . . . . . . . . .412B

Working with Wi-Fi . . . . . . . . . . . . . . . . . . . . . . .412B

Working with Bluetooth . . . . . . . . . . . . . . . . . . . .414B

Checking for the Existence of Bluetooth Hardware . . . . . . . . . . . . . . . . . . . . . . . . . .415B

Page 23: The Android Developer's Collection

xxii Contents

Enabling Bluetooth . . . . . . . . . . . . . . . . . . . . .415B

Querying for Paired Devices . . . . . . . . . . . . . .416B

Discovering Devices . . . . . . . . . . . . . . . . . . . .416B

Establishing Connections Between Devices . . .416B

Monitoring the Battery . . . . . . . . . . . . . . . . . . . .417B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .420B

References and More Information . . . . . . . . . . . .421B

V: More Android Application Design Principles

20 Working with Notifications . . . . . . . . . . . . . .423BNotifying the User . . . . . . . . . . . . . . . . . . . . . . . .423B

Notifying with the Status Bar . . . . . . . . . . . . . . . .424B

Using the NotificationManagerService . . . . . . . . . . . . . . . . . . . . . . . . . . . .425B

Creating a Simple Text Notification with an Icon . . . . . . . . . . . . . . . . . . . . . . . .425B

Working with the Notification Queue . . . . . . . .426B

Updating Notifications . . . . . . . . . . . . . . . . . .427B

Clearing Notifications . . . . . . . . . . . . . . . . . . .428B

Vibrating the Phone . . . . . . . . . . . . . . . . . . . . . .429B

Blinking the Lights . . . . . . . . . . . . . . . . . . . . . . .430B

Making Noise . . . . . . . . . . . . . . . . . . . . . . . . . . .431B

Customizing the Notification . . . . . . . . . . . . . . . .432B

Designing Useful Notifications . . . . . . . . . . . . . . .434B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .434B

References and More Information . . . . . . . . . . . .435B

21 Working with Services . . . . . . . . . . . . . . . . . .437BDetermining When to Use Services . . . . . . . . . . .437B

Understanding the Service Lifecycle . . . . . . . . . .438B

Creating a Service . . . . . . . . . . . . . . . . . . . . . . .438B

Controlling a Service . . . . . . . . . . . . . . . . . . . . .443B

Implementing a Remote Interface . . . . . . . . . . . .444B

Implementing a Parcelable Class . . . . . . . . . . . . .446B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .449B

References and More Information . . . . . . . . . . . .449B

Page 24: The Android Developer's Collection

xxiiiContents

22 Extending Android Application Reach . . . . . .451BEnhancing Your Applications . . . . . . . . . . . . . . . .451B

Working with App Widgets . . . . . . . . . . . . . . . . . .452B

Creating an App Widget . . . . . . . . . . . . . . . . .453B

Installing an App Widget . . . . . . . . . . . . . . . . .460B

Becoming an App Widget Host . . . . . . . . . . . .460B

Working with Live Wallpapers . . . . . . . . . . . . . . .461B

Creating a Live Wallpaper . . . . . . . . . . . . . . . .462B

Installing a Live Wallpaper . . . . . . . . . . . . . . .465B

Acting as a Content Type Handler . . . . . . . . . . . .466B

Determining Intent Actions and MIME Types . . . . .467B

Implementing the Activity to Process the Intents . . . . . . . . . . . . . . . . . . . . . . . . . . . .468B

Registering the Intent Filter . . . . . . . . . . . . . .469B

Making Application Content Searchable . . . . . . . .469B

Enabling Searches Within Your Application . . . .470B

Enabling Global Search . . . . . . . . . . . . . . . . .478B

Working with Live Folders . . . . . . . . . . . . . . . . . .480B

Creating Live Folders . . . . . . . . . . . . . . . . . . .481B

Installing a Live Folder . . . . . . . . . . . . . . . . . .485B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .487B

References and More Information . . . . . . . . . . . .487B

23 Managing User Accounts and Synchronizing User Data . . . . . . . . . . . . . . . . . . . . . . . . . .489B

Managing Accounts with the Account Manager . . .489B

Synchronizing Data with Sync Adapters . . . . . .490B

Using Backup Services . . . . . . . . . . . . . . . . . . . .491B

Choosing a Remote Backup Service . . . . . . . .492B

Implementing a Backup Agent . . . . . . . . . . . . .492B

Backing Up and Restoring Application Data . . .496B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .497B

References and More Information . . . . . . . . . . . .497B

24 Handling Advanced User Input . . . . . . . . . . . .499BWorking with Textual Input Methods . . . . . . . . . . .499B

Working with Software Keyboards . . . . . . . . . .499B

Working with Text Prediction and User Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . .502B

Page 25: The Android Developer's Collection

xxiv Contents

Exploring the Accessibility Framework . . . . . . . . .502B

Leveraging Speech Recognition Services . . . . .503B

Leveraging Text-To-Speech Services . . . . . . . . .506B

Working with Gestures . . . . . . . . . . . . . . . . . . . .508B

Detecting User Motions Within a View . . . . . . .509B

Handling Common Single-Touch Gestures . . . . . . .509B

Handling Common Multi-Touch Gestures . . . . .516B

Making Gestures Look Natural . . . . . . . . . . . .518B

Working with the Trackball . . . . . . . . . . . . . . . . . .519B

Handling Screen Orientation Changes . . . . . . . . .519B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .522B

References and More Information . . . . . . . . . . . .522B

25 Targeting Different Device Configurations andLanguages . . . . . . . . . . . . . . . . . . . . . . . . . .523BMaximizing Application Compatibility . . . . . . . . . .523B

Designing User Interfaces for Compatibility . . . . .525B

Supporting Specific Screen Types . . . . . . . . . .526B

Working with Nine-Patch Stretchable Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . .526B

Using the Working Square Principle . . . . . . . . .528B

Providing Alternative Application Resources . . . . .531B

Working with Alternative Resource Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . .531B

Providing Resources for Different Orientations . . . . . . . . . . . . . . . . . . . . . . . .537B

Using Alternative Resources Programmatically . . . . . . . . . . . . . . . . . . . . .538B

Organizing Application Resources Efficiently . . . . . . . . . . . . . . . . . . . . . . . . . .538B

Internationalizing Applications . . . . . . . . . . . . . . .539B

Internationalization Using Alternative Resources . . . . . . . . . . . . . . . . . . . . . . . . . .540B

Implementing Locale Support Programmatically . . . . . . . . . . . . . . . . . . . . .544B

Targeting Different Device Configurations . . . . . . .545B

Supporting Hardware Configurations . . . . . . . .545B

Targeting Different Android SDK Versions . . . . .546B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .548B

References and More Information . . . . . . . . . . . .549B

Page 26: The Android Developer's Collection

xxvContents

VI: Deploying Your Android Application to the World

26 The Mobile Software Development Process . .551BAn Overview of the Mobile Development

Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .551B

Choosing a Software Methodology . . . . . . . . . . . .552B

Understanding the Dangers of Waterfall Approaches . . . . . . . . . . . . . . . . . . . . . . . . .552B

Understanding the Value of Iteration . . . . . . . .553B

Gathering Application Requirements . . . . . . . . . .553B

Determining Project Requirements . . . . . . . . .553B

Developing Use Cases for Mobile Applications . . . . . . . . . . . . . . . . . . . . . . . .555B

Incorporating Third-Party Requirements . . . . . .555B

Managing a Device Database . . . . . . . . . . . . .555B

Assessing Project Risks . . . . . . . . . . . . . . . . . . .558B

Identifying Target Devices . . . . . . . . . . . . . . . .558B

Acquiring Target Devices . . . . . . . . . . . . . . . . .560B

Determining Feasibility of Application Requirements . . . . . . . . . . . . . . . . . . . . . . .561B

Understanding Quality Assurance Risks . . . . . .561B

Writing Essential Project Documentation . . . . . . .562B

Developing Test Plans for Quality Assurance Purposes . . . . . . . . . . . . . . . . . . . . . . . . . .562B

Providing Documentation Required by Third Parties . . . . . . . . . . . . . . . . . . . . . . . .563B

Providing Documentation for Maintenance and Porting . . . . . . . . . . . . . . . . . . . . . . . . . . . .563B

Leveraging Configuration Management Systems . .563B

Choosing a Source Control System . . . . . . . . .563B

Implementing an Application Version System That Works . . . . . . . . . . . . . . . . . . . . . . . . .564B

Designing Mobile Applications . . . . . . . . . . . . . . .564B

Understanding Mobile Device Limitations . . . .564B

Exploring Common Mobile Application Architectures . . . . . . . . . . . . . . . . . . . . . . . .564B

Designing for Extensibility and Maintenance . .565B

Designing for Application Interoperability . . . . .566B

Developing Mobile Applications . . . . . . . . . . . . . .567B

Testing Mobile Applications . . . . . . . . . . . . . . . . .567B

Page 27: The Android Developer's Collection

xxvi Contents

Deploying Mobile Applications . . . . . . . . . . . . . . .568B

Determining Target Markets . . . . . . . . . . . . . .568B

Supporting and Maintaining Mobile Applications . .568B

Track and Address Crashes Reported by Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . .569B

Testing Firmware Upgrades . . . . . . . . . . . . . . .569B

Maintaining Adequate Application Documentation . . . . . . . . . . . . . . . . . . . . . .569B

Managing Live Server Changes . . . . . . . . . . . .569B

Identifying Low-Risk Porting Opportunities . . . .569B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .570B

References and More Information . . . . . . . . . . . .570B

27 Designing and Developing Bulletproof AndroidApplications . . . . . . . . . . . . . . . . . . . . . . . . .571BBest Practices in Designing Bulletproof MobileApplications . . . . . . . . . . . . . . . . . . . . . . . . . . . .571B

Meeting Mobile Users’ Demands . . . . . . . . . .572B

Designing User Interfaces for Mobile Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . .572B

Designing Stable and Responsive Mobile Applications . . . . . . . . . . . . . . . . . . . . . . . .573B

Designing Secure Mobile Applications . . . . . . .574B

Designing Mobile Applications for Maximum Profit . . . . . . . . . . . . . . . . . . . . . . . . . . . . .575B

Leveraging Third-Party Standards for Android Application Design . . . . . . . . . . . . . . . . . . . .576B

Designing Mobile Applications for Ease of Maintenance and Upgrades . . . . . . . . . . . . .576B

Leveraging Android Tools for Application Design . . . . . . . . . . . . . . . . . . . . . . . . . . . .578B

Avoiding Silly Mistakes in Android Application Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .578B

Best Practices in Developing Bulletproof Mobile Applications . . . . . . . . . . . . . . . . . . . . . . . . . . .579B

Designing a Development Process That Works for Mobile Development . . . . . . . . . . .579B

Testing the Feasibility of Your Application Early and Often . . . . . . . . . . . . . . . . . . . . . .579B

Using Coding Standards, Reviews, and Unit Tests to Improve Code Quality . . . . . . . . . . .580B

Page 28: The Android Developer's Collection

xxviiContents

Handling Defects Occurring on a Single Device . . . . . . . . . . . . . . . . . . . . . . . . . . . .582B

Leveraging Android Tools for Development . . . .583B

Avoiding Silly Mistakes in Android Application Development . . . . . . . . . . . . . . . . . . . . . . . .583B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .583B

References and More Information . . . . . . . . . . . .584B

28 Testing Android Applications . . . . . . . . . . . . .585BBest Practices in Testing Mobile Applications . . . .585B

Designing a Mobile Application Defect Tracking System . . . . . . . . . . . . . . . . . . . . .585B

Managing the Testing Environment . . . . . . . . .587B

Maximizing Testing Coverage . . . . . . . . . . . . .589B

Leveraging Android Tools for Android Application Testing . . . . . . . . . . . . . . . . . . . .595B

Avoiding Silly Mistakes in Android Application Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . .595B

Outsourcing Testing Responsibilities . . . . . . . .596B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .596B

References and More Information . . . . . . . . . . . .596B

29 Selling Your Android Application . . . . . . . . . .597BChoosing the Right Distribution Model . . . . . . . . .597B

Packaging Your Application for Publication . . . . . .598B

Preparing Your Code to Package . . . . . . . . . . .599B

Packing and Signing Your Application . . . . . . . .600B

Testing the Release Version of Your Application Package . . . . . . . . . . . . . . . . . . . . . . . . . . .603B

Certifying Your Android Application . . . . . . . . .603B

Distributing Your Applications . . . . . . . . . . . . . . .603B

Selling Your Application on the Android Market . . . . . . . . . . . . . . . . . . . . . . . . . . . .603B

Selling Your Application on Your Own Server . .609B

Selling Your Application Using Other Alternatives . . . . . . . . . . . . . . . . . . . . . . . . .610B

Protecting Your Intellectual Property . . . . . . . .611B

Billing the User . . . . . . . . . . . . . . . . . . . . . . .611B

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .612B

References and More Information . . . . . . . . . . . .612B

Page 29: The Android Developer's Collection

xxviii Contents

VII: Appendixes

A The Android Emulator Quick-Start Guide . . . .613BSimulating Reality: The Emulator’s Purpose . . . . .613B

Working with Android Virtual Devices (AVDs) . . . . .615B

Using the Android SDK and AVD Manager . . . .616B

Creating an AVD . . . . . . . . . . . . . . . . . . . . . . .616B

Launching the Emulator with a Specific AVD . . . . .620B

Configuring Emulator Startup Options . . . . . . .621B

Launching an Emulator to Run an Application . . . . . . . . . . . . . . . . . . . . . . . . .621B

Launching an Emulator from the Android SDK and AVD Manager . . . . . . . . . . . . . . . . .623B

Configuring the GPS Location of the Emulator . . .623B

Calling Between Two Emulator Instances . . . . . . .625B

Messaging Between Two Emulator Instances . . . .625B

Interacting with the Emulator Through the Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .628B

Using the Console to Simulate Incoming Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .628B

Using the Console to Simulate SMS Messages . . . . . . . . . . . . . . . . . . . . . . . . . .629B

Using the Console to Send GPS Coordinates . . . . . . . . . . . . . . . . . . . . . . . . .630B

Using the Console to Monitor Network Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . .631B

Using the Console to Manipulate Power Settings . . . . . . . . . . . . . . . . . . . . . . . . . . .631B

Using Other Console Commands . . . . . . . . . . .632B

Enjoying the Emulator . . . . . . . . . . . . . . . . . . . . .632B

Understanding Emulator Limitations . . . . . . . . . .632B

B The Android DDMS Quick-Start Guide . . . . . .635BUsing DDMS with Eclipse and as a Stand-Alone

Application . . . . . . . . . . . . . . . . . . . . . . . . . . . .635B

Getting Up to Speed Using Key Features of DDMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .636B

Working with Processes . . . . . . . . . . . . . . . . . . .637B

Attaching a Debugger to an Android Application . . . . . . . . . . . . . . . . . . . . . . . . .638B

Page 30: The Android Developer's Collection

xxixContents

Monitoring Thread Activity of an Android Application . . . . . . . . . . . . . . . . . . . . . . . . .638B

Prompting Garbage Collection (GC) . . . . . . . . .639B

Monitoring Heap Activity . . . . . . . . . . . . . . . . .639B

Monitoring Memory Allocation . . . . . . . . . . . . .640B

Stopping a Process . . . . . . . . . . . . . . . . . . . .640B

Working with the File Explorer . . . . . . . . . . . . . . .641B

Browsing the File System of an Emulator or Device . . . . . . . . . . . . . . . . . . . . . . . . . . . .641B

Copying Files from the Emulator or Device . . . .641B

Copying Files to the Emulator or Device . . . . . .642B

Deleting Files on the Emulator or Device . . . . .642B

Working with the Emulator Control . . . . . . . . . . . .642B

Simulating Incoming Voice Calls . . . . . . . . . . .643B

Simulating Incoming SMS Messages . . . . . . . .643B

Sending a Location Fix . . . . . . . . . . . . . . . . . .643B

Working with Application Logging . . . . . . . . . . . . .644B

Taking Screen Captures of Emulator and Device Screens . . . . . . . . . . . . . . . . . . . . . . . .645B

C The Android Debug Bridge Quick-Start Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . .647B

Listing Connected Devices and Emulators . . . . . .647B

Directing ADB Commands to Specific Devices . . .648B

Starting and Stopping the ADB Server . . . . . . . . .648B

Stopping the ADB Server Process . . . . . . . . . .648B

Starting and Checking the ADB Server Process . . . . . . . . . . . . . . . . . . . . . . . . . . .648B

Issuing Shell Commands . . . . . . . . . . . . . . . . . .649B

Issuing a Single Shell Command . . . . . . . . . . .649B

Using a Shell Session . . . . . . . . . . . . . . . . . .649B

Using the Shell to Start and Stop the Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . .649B

Copying Files . . . . . . . . . . . . . . . . . . . . . . . . . . .650B

Sending Files to a Device or Emulator . . . . . . .650B

Retrieving Files from a Device or Emulator . . . .650B

Installing and Uninstalling Applications . . . . . . . .651B

Installing Applications . . . . . . . . . . . . . . . . . .651B

Reinstalling Applications . . . . . . . . . . . . . . . . .651B

Page 31: The Android Developer's Collection

xxx Contents

Uninstalling Applications . . . . . . . . . . . . . . . .651B

Working with LogCat Logging . . . . . . . . . . . . . .652B

Displaying All Log Information . . . . . . . . . . . . .652B

Including Date and Time with Log Data . . . . . .652B

Filtering Log Information . . . . . . . . . . . . . . . . .652B

Clearing the Log . . . . . . . . . . . . . . . . . . . . . .654B

Redirecting Log Output to a File . . . . . . . . . . .654B

Accessing the Secondary Logs . . . . . . . . . . . .654B

Controlling the Backup Service . . . . . . . . . . . . . .654B

Forcing Backup Operations . . . . . . . . . . . . . . .655B

Forcing Restore Operations . . . . . . . . . . . . . . .655B

Wiping Archived Data . . . . . . . . . . . . . . . . . . .655B

Generating Bug Reports . . . . . . . . . . . . . . . . . . .655B

Using the Shell to Inspect SQLite Databases . . . .656B

Using the Shell to Stress Test Applications . . . . .656B

Letting the Monkey Loose on Your Application . . . . . . . . . . . . . . . . . . . . . . . . .656B

Listening to Your Monkey . . . . . . . . . . . . . . . .656B

Directing Your Monkey’s Actions . . . . . . . . . . .657B

Training Your Monkey to Repeat His Tricks . . . .658B

Keeping the Monkey on a Leash . . . . . . . . . . .658B

Learning More About Your Monkey . . . . . . . . .659B

Installing Custom Binaries via the Shell . . . . . . . .659B

Exploring Other ADB Commands . . . . . . . . . . . . .660B

D Eclipse IDE Tips and Tricks . . . . . . . . . . . . . .661BOrganizing Your Eclipse Workspace . . . . . . . . . . .661B

Integrating with Source Control Services . . . . .661B

Repositioning Tabs Within Perspectives . . . . . .661B

Maximizing Windows . . . . . . . . . . . . . . . . . . .662B

Minimizing Windows . . . . . . . . . . . . . . . . . . . .662B

Viewing Windows Side by Side . . . . . . . . . . . .662B

Viewing Two Sections of the Same File . . . . . .662B

Closing Unwanted Tabs . . . . . . . . . . . . . . . . .662B

Keeping Windows Under Control . . . . . . . . . . .663B

Creating Custom Log Filters . . . . . . . . . . . . . .663B

Writing Code in Java . . . . . . . . . . . . . . . . . . . . . .663B

Using Auto-Complete . . . . . . . . . . . . . . . . . . .664B

Page 32: The Android Developer's Collection

xxxiContents

Formatting Code . . . . . . . . . . . . . . . . . . . . . .664B

Creating New Classes . . . . . . . . . . . . . . . . . .664B

Creating New Methods . . . . . . . . . . . . . . . . . .664B

Organizing Imports . . . . . . . . . . . . . . . . . . . . .664B

Renaming Almost Anything . . . . . . . . . . . . . . .665B

Refactoring Code . . . . . . . . . . . . . . . . . . . . . .665B

Reorganizing Code . . . . . . . . . . . . . . . . . . . . .667B

Providing Javadoc-Style Documentation . . . . . .667B

Resolving Mysterious Build Errors . . . . . . . . . .667B

E The SQLite Quick-Start Guide . . . . . . . . . . . .669BExploring Common Tasks with SQLite . . . . . . . . . .669B

Using the sqlite3 Command-Line Interface . . .670B

Launching the ADB Shell . . . . . . . . . . . . . . . .670B

Connecting to a SQLite Database . . . . . . . . . .670B

Exploring Your Database . . . . . . . . . . . . . . . . .671B

Importing and Exporting the Database and Its Data . . . . . . . . . . . . . . . . . . . . . . . . . . .672B

Executing SQL Commands on the Command Line . . . . . . . . . . . . . . . . . . . . . .674B

Using Other sqlite3 Commands . . . . . . . . .675B

Understanding SQLite Limitations . . . . . . . . . .675B

Learning by Example: A Student Grade Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . .675B

Designing the Student Grade Database Schema . . . . . . . . . . . . . . . . . . . . . . . . . . .676B

Creating Simple Tables with AUTOINCREMENT . . . . . . . . . . . . . . . . . . . . .676B

Inserting Data into Tables . . . . . . . . . . . . . . . .677B

Querying Tables for Results with SELECT . . . . .677B

Using Foreign Keys and Composite Primary Keys . . . . . . . . . . . . . . . . . . . . . . . .678B

Altering and Updating Data in Tables . . . . . . . .679B

Querying Multiple Tables Using JOIN . . . . . . . .680B

Using Calculated Columns . . . . . . . . . . . . . . .680B

Using Subqueries for Calculated Columns . . . .682B

Deleting Tables . . . . . . . . . . . . . . . . . . . . . . .682B

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .683B

Page 33: The Android Developer's Collection

This page intentionally left blank

Page 34: The Android Developer's Collection

The AndroidDeveloper’s CookbookBuilding Applications with

the Android SDK

Page 35: The Android Developer's Collection

The Developer’s Library Series from Addison-Wesley provides

practicing programmers with unique, high-quality references and

tutorials on the latest programming languages and technologies they

use in their daily work. All books in the Developer’s Library are written by

expert technology practitioners who are exceptionally skilled at organizing

and presenting information in a way that’s useful for other programmers.

Developer’s Library books cover a wide range of topics, from open-

source programming languages and databases, Linux programming,

Microsoft, and Java, to Web development, social networking platforms,

Mac/iPhone programming, and Android programming.

Visit developers-library.com for a complete list of available products

Developer’s Library Series

Page 36: The Android Developer's Collection

The AndroidDeveloper’s CookbookBuilding Applications with

the Android SDK

James SteeleNelson To

Upper Saddle River, NJ • Boston • Indianapolis • San FranciscoNew York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

Page 37: The Android Developer's Collection

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and the publish-er was aware of a trademark claim, the designations have been printed with initial capitalletters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors or omis-sions. No liability is assumed for incidental or consequential damages in connection with orarising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk pur-chases or special sales, which may include electronic versions and/or custom covers andcontent particular to your business, training goals, marketing focus, and branding interests.For more information, please contact:

U.S. Corporate and Government Sales(800) [email protected]

For sales outside the United States, please contact:

International [email protected]

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data

Steele, James, 1971-The Android developer's cookbook : building applications with the

Android SDK / James Steele, Nelson To.p. cm.

Includes bibliographical references and index.ISBN-13: 978-0-321-74123-3 (pbk. : alk. paper)ISBN-10: 0-321-74123-4 (pbk. : alk. paper)

1. Application software—Development. 2. Android (Electronic resource)3. Mobile computing. 4. Smartphones—Programming. 5. Operating systems(Computers) I. To, Nelson, 1976- II. Title.

QA76.76.A65S743 2011004.1675—dc22

2010033254

Copyright © 2011 by Pearson Education, Inc.

All rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibited repro-duction, storage in a retrieval system, or transmission in any form or by any means, elec-tronic, mechanical, photocopying, recording, or likewise. For information regarding permis-sions, write to:

Pearson Education, Inc.Rights and Contracts Department501 Boylston Street, Suite 900Boston, MA 02116Fax (617) 671-3447

Images that appear with the link http://www.developer.android.com in the credit line areexact reproductions or modifications of work created and shared by the Android OpenSource Project (http://code.google.com/policies.html) and are used according to termsdescribed in the Creative Commons 2.5 Attribution License (http://creativecommons.org/licenses/by/2.5/).

Text printed in the United States on recycled paper at RR Donnelley, Crawfordsville, Indiana.

First Printing: October 2010

ISBN-10: 0-321-74123-4ISBN-13: 978-0-321-74123-3

Editor-in-ChiefMark Taub

Acquisitions EditorTrina McDonald

DevelopmentEditorMichael Thurston

Managing EditorSandra Schroeder

Project EditorMandie Frank

Copy EditorDeadline DrivenPublishing

IndexerErika Millen

ProofreaderJovana Shirley

Technical EditorsRomin IraniDouglas Jones

PublishingCoordinatorOlivia Basegio

DesignerGary Adair

Page LayoutMark Shirar

Page 38: The Android Developer's Collection

To Wei with love.

Jim

To my dear mom.

Nelson

Page 39: The Android Developer's Collection

PrefaceAndroid is the fastest growing mobile operating system (OS).With over 30 smartphonesintroduced in the last year and over 10,000 applications (apps) being added every month,the Android ecosystem is growing as well.There is enough diversity in device featuresand wireless carriers to appeal to just about anyone.

Netbooks have always been a natural platform to adopt Android, but the inertiabehind Android has fed the growth further into televisions and even automobiles. Manyof the world’s largest corporations—from banks to fast food chains to airlines—ensure apresence in Android and offer compatible services.Android developers have manyopportunities, and relevant apps reach more people than ever before, increasing the satis-faction of creating a relevant app.

Why an Android Cookbook?The Android OS is simple to learn, and Google provides many libraries to make it easyto implement rich and complex applications.The only aspect lacking, as mentioned bymany in the Android developer community, is clear and well-explained documentation.The fact that Android is open source means anyone can dive in and reverse engineersome documentation. Many developer bulletin boards have excellent examples deducedusing exactly this method. Still, a book that has a consistent treatment across all areas ofthe OS is useful.

In addition, a clear working example is worth a thousand words of documentation.Developers faced with a problem usually prefer to do a form of extreme programming;that is, they find examples of working code that does something close to the solutionand modify or extend it to meet their needs.The examples also serve as a way to see thecoding style and help to shape other parts of the developer’s code.

This Android Cookbook serves to fill a need by providing many various self-con-tained recipes.As each recipe is introduced, the main concepts of the Android OS arealso explained.

Who Should Read This Book?Users who are writing their own Android applications will get the most out of thiscookbook. Basic familiarity with Java and the Eclipse development environment isassumed, but not required for the majority of the book. Java is a modular language andmost (if not all) of the example recipes can be incorporated with minimal change to thereader’s own Android project.The motivation for each topic lends itself well for use as anAndroid course supplement.

Page 40: The Android Developer's Collection

Utilizing RecipesIn general, the code recipes in this cookbook are self-contained and include all theinformation necessary to run a working application on an Android device. Chapters 1and 2 give an introduction to the overall use of Android, but feel free to jump aroundand start using whatever is necessary.

This book is written first as a reference, providing knowledge mostly by examplewith greatest benefits through implementation of the recipes of interest.The main tech-nique introduced in each recipe is specified in the section heading. However, additionaltechniques are included in each recipe as needed to support the main recipe.

After reading this book, a developer shouldn Be able to write an Android Application from scratch.n Be able to write code that works across multiple versions of Android.n Be able to utilize the various Application Programming Interfaces (APIs) provided

in Android.n Have a large reference of code snippets to quickly assimilate into applications.n Appreciate the various ways to do the same task in Android and the benefits of

each.n Understand the unique aspects of Android programming techniques.

Book StructureChapter 1,“Overview of Android,” provides an introduction to all aspects of Androidoutside of the code itself. It is the only chapter that doesn’t include recipes, but providesuseful background material. Chapter 2,“Application Basics:Activities and Intents,” pro-vides an overview of the four Android components and explanation of how an Androidproject is organized. It also focuses on the activity as a main application building block.Chapter 3,“Threads, Services, Receivers, and Alerts,” introduces background tasks such asthreads, services, and receivers, as well as notification methods for these background tasksusing alerts. Chapter 4,“User Interface Layout,” covers the user interface screen layoutand views, and Chapter 5,“User Interface Events,” covers the user initiated events suchas touch events and gestures.

Chapter 6,“Multimedia Techniques,” covers multimedia manipulation and record andplayback of audio and video. Chapter 7,“Hardware Interface,” introduces the hardwareAPIs available on Android devices and how to utilize them. Chapter 8,“Networking,”discusses interaction outside of the Android device with SMS, web browsing, and socialnetworking. Chapter 9,“Data Storage Methods,” covers various data storage techniquesavailable in Android including SQLite. Chapter 10,“Location-Based Services,” focuses onaccessing the location through various methods such as GPS and utilizing services suchas the Google Maps API. Chapter 11,“Advanced Android Development,” provides someadvanced techniques in Android including customizing views, using native code for

viiPreface

Page 41: The Android Developer's Collection

faster processing, and utilizing the Android Backup Manager. Finally, Chapter 12,“Debugging,” provides the testing and debugging framework useful throughout thedevelopment cycle.

Additional ReferencesThere are many online references for Android.A few essential ones aren Android Source Code: http://source.android.com/n Android Developer Pages: http://developer.android.com/n Android Developer Forums: http://www.svcAndroid.com/n Open Source Directory: http://osdir.com/n Stack Overflow Discussion Threads: http://stackoverflow.com/n Talk Android Developer Forums: http://www.talkandroid.com/android-forums/

viii Preface

Page 42: The Android Developer's Collection

About the AuthorsJames Steele was doing post-doctoral work in physics at MIT when he decided to joina startup in Silicon Valley. Fifteen years later and he continues to innovate, bringingresearch projects to production in both the consumer and mobile market. He activelypresents and participates in various Silicon Valley new technology groups.

Nelson To has more than ten applications of his own in the Android Market. He also hasworked on enterprise Android applications for Think Computer, Inc. (PayPhone),AOL(AIM), Stanford University (Education App), and Logitech (Google TV). He also assistsin organizing the SiliconValley Android Meetup Community and teaches Android classesboth in the Bay Area and China.

Page 43: The Android Developer's Collection

This page intentionally left blank

Page 44: The Android Developer's Collection

Table 2.1 The Four Possible Components of an Android Application

Functionality Java Base Class Examples

Focused thing a user can do Activity Edit a note, play a game

Background process Service Play music, update weather icon

Receive messages BroadcastReceiver Trigger alarm upon event

Store and retrieve data ContentProvider Open a phone contact

2Application Basics:

Activities and Intents

Each Android application is represented by a single Android project.An overview of theproject structure, including a brief introduction to the basic building blocks of an applica-tion, is provided as useful background information for the recipes in this book.Then thefocus of this chapter turns to activities and the intents that launch them.

Android Application OverviewAn Android application consists of various functionalities. Some examples are editing anote, playing a music file, ringing an alarm, or opening a phone contact.These functional-ities can be classified into four different Android components, shown in Table 2.1, each ofwhich is specified by a Java base class.

Every application is made up of one or more of these components.They are instantiatedby the Android operating system (OS) as needed. Other applications are allowed to usethem, too, within the specified permissions.

As multiple functionalities play out in the OS (some not even related to the intendedapplication, such as an incoming phone call), each component goes through a lifecycle ofgetting created, focused, defocused, and destroyed.The default behavior can be overriddenfor a graceful operation, such as saving variables or restoring user interface (UI) elements.

Page 45: The Android Developer's Collection

With the exception of ContentProvider, each component is activated by an asyn-chronous message called an Intent.The Intent can contain a Bundle of supportinginformation describing the component.This provides a method of passing informationbetween components.

The rest of this chapter demonstrates the previous concepts using the most commoncomponent: the Activity. Because activities almost always specify an interaction with auser, a window is automatically created with each activity.Therefore, a short introductionto the UI is also included. Of the other components, Service and BroadcastReceiver

are covered in Chapter 3,“Threads, Services, Receivers, and Alerts,” andContentProvider is covered in Chapter 9,“Data Storage Methods.”

Recipe: Creating a Project and an ActivityA straightforward way to create an Android project or any of its components is to use theEclipse Integrated Development Environment (IDE).This method ensures proper setupof the supporting files.The steps to create a new Android project are

1. In Eclipse, choose File → New → Android Project.This displays a New AndroidProject creation screen.

2. Fill in the Project name, such as SimpleActivityExample.

3. Select a Build Target from the choices provided.These choices are based on theSoftware Development Kit (SDK) versions that are installed on the developmentcomputer.

4. Fill in the Application name, such as Example of Basic Activity.

5. Fill in the Package name, such as com.cookbook.simple_activity.

6. To create the main activity in the same step, be sure Create Activity is checked andfill in an Activity name, such as SimpleActivity.

All activities extend the abstract class Activity or one of its subclasses.The entry point toeach activity is the onCreate() method. It is almost always overridden to initialize theactivity, such as setting up the UI, creating button listeners, initializing parameters, andstarting threads.

If the main activity is not created with the project or another activity needs to beadded, the steps to create an activity are

1. Create a class to extend Activity. (In Eclipse, this can be done by right-clickingon the project, choosing New → Class, and then specifying android.app.Activity as the super class.)

2. Override the onCreate() function. (In Eclipse, this can be done by right-clickingon the class file, choosing Source → Override/Implement Methods..., and thenchecking the onCreate() method.)

24A Chapter 2 Application Basics: Activities and Intents

Page 46: The Android Developer's Collection

25AAndroid Application Overview

3. As with most overridden functions, it must invoke the super class method, too; oth-erwise, an exception may be thrown at run-time. Here, the super.onCreate()should be called first to properly initialize the activity, as shown in Listing 2.1.

Listing 2.1 src/com/cookbook/simple_activity/SimpleActivity.java

package com.cookbook.simple_activity;

import android.app.Activity;

import android.os.Bundle;

public class SimpleActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

}

4. If a UI is used, specify the layout in an XML file in the res/layout/ directory. Hereit is called main.xml, as shown in Listing 2.2.

5. Set the layout of the activity using the setContentView() function and passing itthe resource ID for the XML layout file. Here, it is R.layout.main, as shown inListing 2.1.

Listing 2.2 res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello"

/>

</LinearLayout>

6. Declare the properties of the activity in the AndroidManifest XML file.This is cov-ered in more detail in Listing 2.5.

Page 47: The Android Developer's Collection

Figure 2.1 Android project directory structure,as seen in the Eclipse IDE.

Note that the string resources are defined in the strings.xml file in the res/values/folder, as shown in Listing 2.3.This provides a central place for all strings in case textneeds to be changed or reused.

Listing 2.3 res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello">Hello World, SimpleActivity!</string>

<string name="app_name">SimpleActivity</string>

</resources>

Now a more detailed look at the directory structure of this project and the additionalauto-generated content is explored.

Directory Structure of Project and Autogenerated ContentFigure 2.1 shows an example project structure, as seen from the Eclipse Package Explorer.

26A Chapter 2 Application Basics: Activities and Intents

With the exception of the Android 2.0 library, the project structure is a mix of user-generated and auto-generated files.

Page 48: The Android Developer's Collection

27AAndroid Application Overview

User-generated files include

n src/ contains the Java packages the developer writes or imports for the application.Each package can have multiple .java files representing different classes.

n res/layout/ contains the XML files that specify the layout of each screen.n res/values/ contains the XML files used as references by other files.n res/drawable-hdpi/, res/drawable-mdpi/, and res/drawable-ldpi/ are directories

that contain pictures the application uses.They have high, medium, and low dots-per-inch resolution, respectively.

n assets/ contains additional nonmedia files the application uses.n AndroidManifest.xml specifies the project to the Android OS.

Autogenerated files include

n gen/ contains autogenerated code, including the generated class R.java.

n default.properties contains project settings.Although autogenerated, it should bekept under revision control.

An application’s resources include XML files describing the layout, XML files describingvalues such as strings, labels of UI elements, and additional supporting files such aspictures and sounds.At compile time, references to the resources are gathered into anautogenerated wrapper class called R.java. The Android Asset Packaging Tool (aapt)autogenerates this file. Listing 2.4 shows what it looks like for the “Creating a Project and an Activity” recipe.

Listing 2.4 gen/com/cookbook/simple_activity/R.java

/* AUTO-GENERATED FILE. DO NOT MODIFY.

*

* This class was automatically generated by the

* aapt tool from the resource data it found. It

* should not be modified by hand.

*/

package com.cookbook.simple_activity;

public final class R {

public static final class attr {

}

public static final class drawable {

public static final int icon=0x7f020000;

}

public static final class layout {

public static final int main=0x7f030000;

Page 49: The Android Developer's Collection

28A Chapter 2 Application Basics: Activities and Intents

Table 2.2 How Different Resources Are Referenced from Within Java and XML Files

Resource Reference in Java Reference in XML

res/layout/main.xml R.layout.main @layout/main

res/drawable-hdpi/icon.png R.drawable.icon @drawable/icon

@+id/home_button R.id.home_button @id/home_button

<string name="hello"> R.string.hello @string/hello

}

public static final class string {

public static final int app_name=0x7f040001;

public static final int hello=0x7f040000;

}

}

Here, each resource is mapped to a unique integer value. In this way, the R.java classprovides a way to reference external resources within Java code. For example, to referencethe main.xml layout file in Java, the R.layout.main integer is used.To reference thesame within XML files, the "@layout/main" string is used.

Referencing resources from within Java or XML files is demonstrated in Table 2.2.Note that to define a new button ID called home_button, the plus sign is added to theidentifying string: @+id/home_button. More complete details on resources are given inChapter 4,“User Interface Layout,” but this suffices to cover the recipes in this chapter.

Android Package and Manifest FileThe Android project, sometimes also referred to as an Android package, is a collection ofJava packages. Different Android packages can have the same Java package names, whereasthe Android package name must be unique across all applications installed on theAndroid device.

For the OS to access them, each application must declare its available components in asingle AndroidManifest XML file. In addition, this file contains the required permissionsand behavior for the application to run. Listing 2.5 shows what it looks like for the “Cre-ating a Project and an Activity” recipe.

Listing 2.5 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.cookbook.simple_activity"

android:versionCode="1"

android:versionName="1.0">

<application android:icon="@drawable/icon"

Page 50: The Android Developer's Collection

29AAndroid Application Overview

android:label="@string/app_name">

<activity android:name=".SimpleActivity"

android:label="@string/app_name">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

<uses-sdk android:minSdkVersion="3" />

</manifest>

The first line is required and standard across all XML files in Android to specify theencoding.The manifest element defines the Android package name and version.TheversionCode is an integer that can be evaluated in programs to determine the upgrade ordowngrade relationship.The versionName represents a human readable format that canhave major and minor revisions declared.

The application element defines the icon and label the user sees from the Androiddevice menu.The label is a string and should be short enough to display under the iconon a user’s device. Generally the name can be up to two words of ten characters eachwithout being cut off.

The activity element defines the main activity that is launched when the applicationis started and the name shown in the title bar when the activity is active. Here, the Javapackage name needs to be specified, which is com.cookbook.simple_activity.SimpleActivity in this case. Because the Java package name is usually the same as the Android package name, the shorthand notation is often used: .SimpleActivity.However, it is best to remember that the Android package and Java package are distinct.

The intent-filter element informs the Android system of the capabilities of thecomponent. It can have multiple action, category, or data elements for this purpose.This isseen as it is utilized in different recipes.

The uses-sdk element defines the application programming interface (API) levelrequired to run this application. In general, the API level is specified as follows:

<uses-sdk android:minSdkVersion="integer"

android:targetSdkVersion="integer"

android:maxSdkVersion="integer" />

Because the Android OS is constructed to be forward compatible, the maxSdkVersion ishighly discouraged and not even adhered on devices with Android 2.0.1 or later. Specify-ing the targetSdkVersion is not required, but allows devices of the same SDK version todisable compatibility settings that might speed up operation.The minSdkVersion shouldalways be specified to ensure the application does not crash when run on a platform that

Page 51: The Android Developer's Collection

30A Chapter 2 Application Basics: Activities and Intents

does not support the required features in the application.Always choose the lowest APIlevel possible when specifying this.

The AndroidManifest can also contain permission settings needed to run the applica-tion. More complete details about the options are provided in later chapters, but this suf-fices to cover the recipes in this chapter.

Renaming Parts of an ApplicationSometimes a portion of an Android project needs to be renamed. Maybe a file was copiedmanually into the project, such as from this book. Maybe the application name haschanged during development, and it needs to be reflected in the filesystem tree.Auto-matic tools help with this and ensure cross-references are automatically updated. Forexample, in the Eclipse IDE, the different ways to rename portions of an application are

n Rename the Android project, as follows:

1. Right-click the project and Refactor → Move to a new directory in thefilesystem.

2. Right-click the project and Refactor → Rename the project.n Rename an Android package, as follows:

1. Right-click the package and Refactor → Rename the package.

2. Edit the AndroidManifest.xml to ensure the new package name is reflected.n Rename an Android class (such as the major components Activity, Service,BroadcastReceiver, ContentProvider), as follows:

1. Right-click the .java file and Refactor → Rename the class.

2. Edit the AndroidManifest.xml to ensure the android:name has the newcomponent name.

Note that renaming other files, such as XML files, usually requires manually changing thecorresponding references in the Java code.

Activity LifecycleEach activity in an application goes through its own lifecycle. Once and only once whenan activity is created, is the onCreate() function executed. If the activity exits, theonDestroy() function is executed. In between, various events can lead to the activitybeing in multiple different states, as illustrated in Figure 2.2.The next recipe provides anexample of each of these functions.

Page 52: The Android Developer's Collection

31AActivity Lifecycle

Activity isrunning

Activity isshut down

onResume()

onDestroy()

The activity is nolonger visible

onStart() onRestart()

onCreate()

Activitystarts

onPause()

The activity comesto the foreground

Process iskilled

User navigatesback to the activity

Other applicationsneed memory

onStop()

The activity comesto the foreground

Another activity comesin front of the activity

Figure 2.2 Activity Lifecycle from http://developer.android.com/.

Recipe: Utilizing Other Lifecycle FunctionsThe following recipe provides a simple way to see the activity lifecycle in action. Forillustration purposes, each overridden function is explicit and a Toast command is addedto show on screen when the function is entered (more detail on the Toast widget is

Page 53: The Android Developer's Collection

32A Chapter 2 Application Basics: Activities and Intents

provided in Chapter 3).The activity is shown in Listing 2.6. Run it on an Android deviceand try various cases. In particular, note the following:

n Changing the screen orientation destroys and recreates the activity from scratch.n Pressing the Home button pauses the activity, but does not destroy it.n Pressing the Application icon might start a new instance of the activity, even if the

old one was not destroyed.n Letting the screen sleep pauses the activity and the screen awakening resumes it.

(This is similar to taking an incoming phone call.)

Listing 2.6 src/com/cookbook/activity_lifecycle/ActivityLifecycle.java

package com.cookbook.activity_lifecycle;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Toast;

public class ActivityLifecycle extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();

}

@Override

protected void onStart() {

super.onStart();

Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();

}

@Override

protected void onResume() {

super.onResume();

Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();

}

@Override

protected void onRestart() {

super.onRestart();

Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT).show();

}

Page 54: The Android Developer's Collection

33AActivity Lifecycle

@Override

protected void onPause() {

Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();

super.onPause();

}

@Override

protected void onStop() {

Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();

super.onStop();

}

@Override

protected void onDestroy() {

Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();

super.onDestroy();

}

}

As seen here, various common actions by the user can cause the activity to be paused,killed, or even launch multiple versions of the application. Before moving on, it is worthmentioning two additional simple recipes that can control this behavior.

Recipe: Forcing Single Task ModeAs an application is navigated away from and launched again, it can lead to multipleinstances of the activity on the device. Eventually the redundant instance of the activity iskilled to free up memory, but in the meantime, it can lead to odd situations.To avoidthese, the developer can control this behavior for each activity in the AndroidManifest.

To ensure only one instance of the activity runs on the device, specify the following inan activity element that has the MAIN and LAUNCHER intent filters:

android:launchMode="singleInstance"

This keeps a single instance of each activity in a task at all times. In addition, any childactivity is launched as its own task.To constrain even further to only have a single task forall activities of an application, use the following:

android:launchMode="singleTask"

This allows the activities to share information easily as the same task.In addition, it might be desirable to retain the task state, regardless of how a user navi-

gates to the activity. For example, if a user leaves the application and relaunches it later,the default behavior often resets the task to its initial state.To ensure the user always

Page 55: The Android Developer's Collection

34A Chapter 2 Application Basics: Activities and Intents

returns to the task in its last state, specify the following in the activity element of theroot activity of a task:

android:alwaysRetainTaskState="true"

Recipe: Forcing Screen OrientationAny Android device with an accelerometer can determine which way is down.As thedevice is tilted from portrait to landscape mode, the default action is to rotate the applica-tion view accordingly. However, as seen from the “Other Lifecycle Functions” recipe, theactivity is destroyed and restarted on screen orientation changes.When this happens, thecurrent state of the activity might be lost, disrupting the user experience.

One option to handle screen orientation changes gracefully is to save state informa-tion before the change and restore information after the change.A simpler method thatmight be useful is to force the screen orientation to stay constant. For each activity inthe AndroidManifest, the screenOrientation can be specified. For example, to specifythat the activity always stays in portrait mode, the following can be added to theactivity element:

android:screenOrientation="portrait"

Similarly, landscape mode can be specified using the following:

android:screenOrientation="landscape"

However, the previous still causes the activity to be destroyed and restarted when a hardkeyboard is slid out.Therefore, a third method is possible:Tell the Android system that theapplication should handle orientation and keyboard slide-out events.This is done byadding the following attribute to the activity element:

android:configChanges="orientation|keyboardHidden"

This can be used alone or in combination with the screenOrientation attribute tospecify the required behavior to the application.

Recipe: Saving and Restoring Activity InformationWhenever an activity is about to be killed, the onSaveInstanceState() function iscalled. Override this to save relevant information that should be retained.When the activ-ity is then recreated, the onRestoreInstanceState() is called. Override this function toretrieve the saved information.This allows for a seamless user experience when an appli-cation undergoes lifecycle changes. Note that most UI states do not need to be managedbecause they are, by default, taken care of by the system.

This function is distinct from onPause(). For example, if another component islaunched in front of the activity, the onPause() function is called. Later, if the activity isstill paused when the OS needs to reclaim resources, it calls onSaveInstanceState()before killing the activity.

Page 56: The Android Developer's Collection

35AMultiple Activities

An example of saving and restoring the instance state consisting of a string and a floatarray is shown in Listing 2.7.

Listing 2.7 Example of onSaveInstanceState() and onRestoreInstanceState()

float[] localFloatArray = {3.14f, 2.718f, 0.577f};

String localUserName = "Euler";

@Override

protected void onSaveInstanceState(Bundle outState) {

super.onSaveInstanceState(outState);

//save the relevant information

outState.putString("name", localUserName);

outState.putFloatArray("array", localFloatArray);

}

@Override

public void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);

//restore the relevant information

localUserName = savedInstanceState.getString("name");

localFloatArray = savedInstanceState.getFloatArray("array");

}

Note that onCreate() also contains the Bundle savedInstanceState. In the case of an activity reinitializing after previously being shut down, the bundle saved inonSaveInstanceState() is also passed to onCreate(). In all cases, the saved bundle ispassed to the onRestoreInstanceState() function, so it is more natural to utilize this torestore states.

Multiple ActivitiesEven the simplest applications have more than one functionality. Hence, there is often aneed to deal with multiple activities. For example, a game can have two activities: a highscores screen and a game screen.A notepad can have three activities: view a list of notes,read a selected note, and edit a selected or new note.

The main activity, as defined in the AndroidManifest XML file, is started when theapplication is started.This activity can launch another activity, usually after a trigger event.This causes the main activity to pause while the secondary activity is active.When thesecondary activity ends, the main activity is brought to the foreground and resumed.

To activate a particular component of the application, an intent naming the compo-nent explicitly is used. If instead the requirements of an application can be specified by

Page 57: The Android Developer's Collection

36A Chapter 2 Application Basics: Activities and Intents

intent filters, an implicit intent can be used.The system then determines the best compo-nent or components to use, even if it is in a separate application or native to the OS. Notethat unlike other activities, implicit intents that reside in other applications do not need tobe declared in the current application’s AndroidManifest file.

Android utilizes implicit intents as often as possible, providing a powerful frameworkfor modular functionality.When a new component is developed that meets the requiredimplicit intent filter, it can be used in place of an Android internal intent. For example, saya new application for displaying phone contacts is loaded on an Android device.When auser selects a contact, the Android system finds all available activities with the properintent filter for viewing contacts and asks the user to decide which one should be used.

Recipe: Using Buttons and TextViewTo fully demonstrate multiple activities, it is useful to use a trigger event.A button press isintroduced here for that purpose.The steps to adding a button to a given layout andassigning an action to a button press are

1. Put a button in the designated layout XML file:<Button android:id="@+id/trigger"

android:layout_width="100dip" android:layout_height="100dip"

android:text="Press this button" />

2. Declare a button that points to the button ID in the layout file:Button startButton = (Button) findViewById(R.id.trigger);

3. Specify a listener for when the button is clicked://setup button listener

startButton.setOnClickListener(new View.OnClickListener() {

//insert onClick here

});

4. Override the onClick function for the listener to do the required action:public void onClick(View view) {

// do something here

}

To show the result of an action, it is useful to change the text on the screen.The steps fordefining a text field and changing it programmatically are

1. Put a text field in the designated layout XML file with an ID. It can also be initial-ized to some value (here, it can be initialized to the string named “hello” in thestrings.xml file):<TextView android:id="@+id/hello_text"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello"

/>

Page 58: The Android Developer's Collection

37AMultiple Activities

2. Declare a TextView that points to the TextView ID in the layout file:private TextView tv = (TextView) findViewById(R.id.hello_text);

3. If the text needs to be changed, use the setText function:tv.setText("new text string");

These two UI techniques are used in the subsequent recipes in this chapter.A morecomplete demonstration of UI techniques is covered in Chapter 4.

Recipe: Launching Another Activity from an EventIn this recipe, MenuScreen is the main activity as shown in Listing 2.8. It launches thePlayGame activity. Here the trigger event is implemented as a button click using theButton widget.

When a user clicks the button, the startGame() function runs; it launches thePlayGame activity.When a user clicks the button in the PlayGame activity, it callsfinish() to return control to the calling activity.The steps for launching an activity are

1. Declare an Intent that points to the activity to be launched.

2. Call startActivity on this intent.

3. Declare the additional activity in the AndroidManifest.

Listing 2.8 src/com/cookbook/launch_activity/MenuScreen.java

package com.cookbook.launch_activity;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MenuScreen extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

//setup button listener

Button startButton = (Button) findViewById(R.id.play_game);

startButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

startGame();

}

});

Page 59: The Android Developer's Collection

38A Chapter 2 Application Basics: Activities and Intents

}

private void startGame() {

Intent llaunchGame = new Intent(this, PlayGame.class);

startActivity(launchGame);

}

}

Provide Current Context in an Anonymous Inner ClassNote the additional consideration needed for launching an activity with a Button press, asshown in Listing 2.8. The intent needs a context. However, using the this shortcut in theonClick function is not properly resolved. Different ways to provide current context in ananonymous inner class are

n Use Context.this instead of this.

n Use getApplicationContext() instead of this.

n Explicitly use the class name MenuScreen.this.

Call a function that is declared at the right context level. This is what is used in Listing 2.8:startGame().

Each of these methods can usually be interchanged. Utilize the one that works best for theclarity of the situation.

The PlayGame activity shown in Listing 2.9 is simply a button with a onClick listenerthat calls finish() to return control to the main activity. More functionality can beadded as needed to this activity, and multiple branches of the code can each lead to theirown finish() calls.

Listing 2.9 src/com/cookbook/launch_activity/PlayGame.java

package com.cookbook.launch_activity;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class PlayGame extends Activity {

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.game);

//setup button listener

Button startButton = (Button) findViewById(R.id.end_game);

startButton.setOnClickListener(new View.OnClickListener() {

Page 60: The Android Developer's Collection

39AMultiple Activities

public void onClick(View view) {

finish();

}

});

}

}

The button must be added to the main layout as shown in Listing 2.10, with the IDplay_game to match what was declared in Listing 2.8. Here, the size of the button is alsodeclared in device-independent pixels (dip), as discussed more in Chapter 4.

Listing 2.10 res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello"

/>

<Button android:id="@+id/play_game"

android:layout_width="100dip" aandroid:layout_height="100dip"

android:text="@string/play_game"

/>

</LinearLayout>

The PlayGame activity references its own button ID end_game in the R.layout.game

layout resource that corresponds to the layout XML file game.xml, as shown inListing 2.11.

Listing 2.11 res/layout/game.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<Button aandroid:id="@+id/end_game"

android:layout_width="100dip" android:layout_height="100dip"

android:ttext="@string/end_game" android:layout_centerInParent="true"

/>

</LinearLayout>

Page 61: The Android Developer's Collection

40A Chapter 2 Application Basics: Activities and Intents

Although the text can be written explicitly in each case, it is good coding practice todefine variables for each string. In this recipe, the two string values play_game andend_game need to be declared in the string XML resource file, as shown in Listing 2.12.

Listing 2.12 res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello">This is the Main Menu</string>

<string name="app_name">LaunchActivity</string>

<string name="play_game">Play game?</string>

<string name="end_game">Done?</string>

</resources>

Finally, the AndroidManifest XML file needs to register a default action to the new classPlayGame, as shown in Listing 2.13.

Listing 2.13 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

android:versionCode="1"

android:versionName="1.0" package="com.cookbook.launch_activity">

<application android:icon="@drawable/icon"

android:label="@string/app_name">

<activity android:name=".MenuScreen"

android:label="@string/app_name">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity aandroid:name=".PlayGame"

android:label="@string/app_name">

<intent-filter>

<action android:name=""android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />

</iintent-filter>

</activity>

</application>

<uses-sdk android:minSdkVersion="3" />

</manifest>

Page 62: The Android Developer's Collection

41AMultiple Activities

Recipe: Launching an Activity for a Result Using Speech to TextIn this recipe, launching an activity for a result is demonstrated. It also demonstrates how toutilize speech to text functionality from Google’s RecognizerIntent and print the resultto the screen. Here, the trigger event is a button press. It launches the RecognizerIntent

activity, which does speech recognition on sound from the microphone and converts itinto text.When finished, the text is passed back to the calling activity.

Upon return, the onActivityResult() function is first called with the returned data,and then the onResume() function is called to continue the activity as normal.The callingactivity can have a problem and not return properly.Therefore, the resultCode shouldalways be checked to ensure RESULT_OK before continuing to parse the returned data.

Note that in general any launched activity that returns data causes the sameonActivityResult() function to be called.Therefore, a request code is customarily usedto distinguish which activity is returning.When the launched activity finishes, it returnscontrol to the calling activity and calls onActivityResult() with the same request code.

The steps for launching an activity for result are

1. Call startActivityForResult() with an intent, defining the launched activity and anidentifying requestCode.

2. Override the onActivityResult() function to check on the status of the result, checkfor the expected requestCode, and parse the returned data.

The steps for using RecognizerIntent are

1. Declare an intent with action ACTION_RECOGNIZE_SPEECH.

2. Add any extras to the intent; at least EXTRA_LANGUAGE_MODEL is re-quired.This can be set as either LANGUAGE_MODEL_FREE_FORM orLANGUAGE_MODEL_WEB_SEARCH.

3. The returned data bundle contains a list of strings with possible matches to theoriginal text. Use data.getStringArrayListExtra to retrieve this data.Thisshould be cast as an ArrayList for use later.

A TextView is used to display the returned text to the screen.The main activity is shownin Listing 2.14.

The additional supporting files needed are the main.xml and strings.xml, which needto define a button and the TextView to hold the result.This is accomplished using Listing2.10 and 2.12 in the “Launching Another Activity from an Event” recipe.The Android-Manifest needs to declare only the main activity, which is the same as the basic “Creatingan Activity” recipe.The RecognizerIntent activity is native to the Android system anddoes not need to be declared explicitly to be utilized.

Page 63: The Android Developer's Collection

42A Chapter 2 Application Basics: Activities and Intents

Listing 2.14 src/com/cookbook/launch_for_result/RecognizerIntent Example.java

package com.cookbook.launch_for_result;

import java.util.ArrayList;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.speech.RecognizerIntent;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

public class RecognizerIntentExample extends Activity {

private static final int RECOGNIZER_EXAMPLE = 1001;

private TextView tv;

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

tv = (TextView) findViewById(R.id.text_result);

//setup button listener

Button startButton = (Button) findViewById(R.id.trigger);

startButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

// RRecognizerIntent prompts for speech and returns text

Intent intent =

new Intent(RRecognizerIntent.ACTION_RECOGNIZE_SPEECH);

intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,

ReccognizerIntent.LANGUAGE_MODEL_FREE_FORM);

intent.putExtra(RecognizerIntent.EXTRA_PROMPT,

"Say a word or phrase\nand it will show as text");

startActivityForResult(intent, RECOGNIZER__EXAMPLE);

}

});

}

@Override

protected void onActivityResult(int requestCode,

int resultCode, Intent data) {

//use a switch statement for more than one request code check

if ((requestCode==RECOGNIZER_EXAMPLE && resultCode==RESULT_OK) {

Page 64: The Android Developer's Collection

43AMultiple Activities

// rreturned data is a list of matches to the speech input

ArrayList<String> resuult =

data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

//display on screen

tv.setTText(result.toString());

}

super.onActivityResult(requestCode, resultCode, data);

}

}

Recipe: Implementing a List of ChoicesA common situation in applications is to provide a user with a list of choices that can beselected by clicking them.This can be easily implemented utilizing ListActivity, a sub-class of Activity, and triggering an event based on what choice was made.

The steps for creating a list of choices are

1. Create a class that extends the ListActivity class instead of the Activity class:public class ActivityExample extends ListActivity {

//content here

}

2. Create a String array of labels for each choice:static final String[] ACTIVITY_CHOICES = new String[] {

"Action 1",

"Action 2",

"Action 3"

};

3. Call setListAdapter() with the ArrayAdapter specifying this list and a layout:setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, ACTIVITY_CHOICES));

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

getListView().setTextFilterEnabled(true);

4. Launch an OnItemClickListener to determine which choice was selected and actaccordingly:getListView().setOnItemClickListener(new OnItemClickListener()

{

@Override

public void onItemClick(AdapterView<?> arg0, View arg1,

int arg2, long arg3) {

switch(arg2) {//extend switch to as many as needed

case 0:

//code for action 1

Page 65: The Android Developer's Collection

44A Chapter 2 Application Basics: Activities and Intents

break;

case 1:

//code for action 2

break;

case 2:

//code for action 3

break;

default: break;

}

}

});

This technique is utilized in the next recipe.

Recipe: Using Implicit Intents for Creating an ActivityImplicit intents do not specify an exact component to use. Instead, they specify the func-tionality required through a filter, and the Android system must determine the best com-ponent to utilize.An intent filter can be either an action, data, or a category.

The most commonly used intent filter is an action, and the most common action isACTION_VIEW.This mode requires a uniform resource identifier (URI) to be specified andthen displays the data to the user. It does the most reasonable action for the given URI.For example, the implicit intents in case 0, 1, and 2 in the following example have thesame syntax but produce different results.

The steps for launching an activity using an implicit intent are

1. Declare the intent with the appropriate filter specified (ACTION_VIEW,ACTION_WEB_SEARCH, and so on).

2. Attach any extra information to the intent required to run the activity.

3. Pass this intent to startActivity().

This is shown for multiple intents in Listing 2.15.

Listing 2.15 src/com/cookbook/implicit_intents/ListActivityExample.java

package com.cookbook.implicit_intents;

import android.app.ListActivity;

import android.app.SearchManager;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

Page 66: The Android Developer's Collection

45AMultiple Activities

import android.widget.ListView;

import android.widget.AdapterView.OnItemClickListener;

public class ListActivityExample extends ListActivity {

static final String[] ACTIVITY_CHOICES = new String[] {

"Open Website Example",

"Open Contacts",

"Open Phone Dialer Example",

"Search Google Example",

"Start Voice Command"

};

final String searchTerms = "superman";

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, ACTIVITY_CHOICES));

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

getListView().setTextFilterEnabled(true);

getListView().setOnItemClickListener(new OnItemClickListener()

{

@Override

public void onItemClick(AdapterView<?> arg0, View arg1,

int arg2, long arg3) {

switch(arg2) {

case 0: //opens web browser and navigates to given website

startActivity(new IIntent(Intent.ACTION_VIEW,

Uri.parse("http://www.android.com/")));

break;

case 1: //opens contacts application to browse contacts

startActivity(new IIntent(Intent.ACTION_VIEW,

Uri.parse("content://contacts/people/")));

break;

case 2: //opens phone dialer and fills in the given number

startActivity(new IIntent(Intent.ACTION_VIEW,

Uri.parse("tel:12125551212")));

break;

case 3: //search Google for the string

Intent iintent= new Intent(Intent.ACTION_WEB_SEARCH );

intent.putExtra(SearchManager.QUERY, searchTTerms);

startActivity(intent);

break;

case 4: //starts the voice command

startActivity(new

Intent(Intent.ACTION_VOICE_COMMAND));

Page 67: The Android Developer's Collection

46A Chapter 2 Application Basics: Activities and Intents

break;

default: break;

}

}

});

}

}

Recipe: Passing Primitive Data Types Between ActivitiesSometimes data needs to be passed to a launched activity. Sometimes a launched activitycreates data that needs to be passed back to the calling activity. For example, a final scoreof a game needs to be returned to a high-scores screen.The different ways to pass infor-mation between activities are

n Declare the relevant variable in the calling activity (for example, public intfinalScore) and set it in the launched activity (for example,CallingActivity.finalScore=score).

n Attach extras onto Bundles (demonstrated here).n Use Preferences to store data to be retrieved later (covered in Chapter 5,“User

Interface Events”).n Use the SQLite database to store data to be retrieved later (covered in Chapter 9).

A Bundle is a mapping from String values to various parcelable types. It can be created byadding extras to an intent.The following example shows data being passed from the mainactivity to the launched activity, where it is modified and passed back.

The variables (in this case, an integer and a String) are declared in the StartScreenactivity.When the intent is created to call the PlayGame class, these variables are attachedto the intent using the putExtra method.When the result is returned from the calledactivity, the variables can be read using the getExtras method.These calls are shown inListing 2.16.

Listing 2.16 src/com/cookbook/passing_data_activities/StartScreen.java

package com.cookbook.passing_data_activities;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

public class StartScreen extends Activity {

private static final int PLAY_GAME = 1010;

Page 68: The Android Developer's Collection

47AMultiple Activities

private TextView tv;

private iint meaningOfLife = 42;

private String userName = "Douglas Adams";

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

tv = (TextView) findViewById(R.id.startscreen_text);

//display initial values

tv.setText(userName + ":" + meaningOfLife);

//setup button listener

Button startButton = (Button) findViewById(R.id.play_game);

startButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

startGame();

}

});

}

@Override

protected void onActivityResult(int requestCode,

int resultCode, Intent data) {

if (requestCode == PLAY_GAME && resultCode == RESULT_OK) {

meaningOfLife == data.getExtras().getInt("returnInt");

userName = data.getExtras().getString("userName");

//show it has changed

tv.setText(userName + ":" + meaningOfLife);

}

super.onActivityResult(requestCode, resultCode, data);

}

private void startGame() {

Intent launchGame = new Intent(this, PlayGame.class);

//passing iinformation to launched activity

launchGame.putExtra("meaningOfLife", meaningOfLife);

launcchGame.putExtra("userName", userName);

startActivityForResult(launchGame, PLAY_GAME);

}

}

Page 69: The Android Developer's Collection

48A Chapter 2 Application Basics: Activities and Intents

The variables passed into the PlayGame activity can be read using the getIntExtra andgetStringExtra methods.When the activity finishes and prepares an intent to return, theputExtra method can be used to return data back to the calling activity.These calls areshown in Listing 2.17.

Listing 2.17 src/com/cookbook/passing_data_activities/PlayGame.java

package com.cookbook.passing_data_activities;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

public class PlayGame extends Activity {

private TextView tv2;

int answer;

String author;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.game);

tv2 = (TextView) findViewById(R.id.game_text);

//reading information passed to this activity

//Get the intent that started this activity

Intent i = getIntent();

//returns --1 if not initialized by calling activity

answer = i.getIntExtra("meaningOfLife", -1);

//returns [] if not initialized by calling activity

author = i.getStringExtraa("userName");

tv2.setText(author + ":" + answer);

//change values for an example of return

answer = answer - 41;

author = author + " Jr.";

//setup button listener

Button startButton = (Button) findViewById(R.id.end_game);

startButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

//return information to calling activity

Page 70: The Android Developer's Collection

49AMultiple Activities

Intent i = getIntent();

i.putExtra("returnInt", aanswer);

i.putExtra("returnStr", author);

setResult(RESULT_OK, i);

finish();

}

});

}

}

Page 71: The Android Developer's Collection

This page intentionally left blank

Page 72: The Android Developer's Collection

Index

Numbers3D images, drawing, 140A-145A

Aaccelerometers, 9A

accept() method, 188A

ACCESS_COARSE_LOCATION permission,252A

ACCESS_FINE_LOCATION permission, 252A

accessing

camera, 169Acontent providers, 244Awireless networks, 191A-193A

ACTION_CALL implicit intent, 185A

ACTION_DIALER implicit intent, 185A

ACTION_DOWN event, 133A

ACTION_MOVE event, 133A

ACTION_POINTER_DOWN event, 133A

ACTION_POINTER_UP event, 133A

ACTION_UP event, 133A

active-matrix organic LED displays(AMOLED), 8A

activities

AudioExamples, 155A-157AAudioExamplesRaw, 161A-163AAudioExamplesSP, 164ABackgroundTimer, 60A-61ABuildingMenus, 122A-124ACameraApplication, 172A-175AChangeFont, 96A-97A

Page 73: The Android Developer's Collection

CheckBoxExample, 106A-107ACountDownTimerExample, 61A-62Acreating, 24A-26ADataStorage, 224A, 226A-227ADataStorageTester, 247A-248ADiary, 237A-238ADiaryContentProvider, 245A-246ADisplayDiaries, 240A-242AEdgeDetection, 56A-57AEula, 228A-231AFlingExample, 131A-132AGestures, 139A-140AGoogleSearch, 206A-208AHandleMessage, 63A-64AHandlerUpdateUi, 93A-94A,

112A-114AHardwareTelephony, 184A-185AImageManipulation, 149A-150Alaunching from events, 37A-40Alaunching with implicit intents,

44A-46Alifecycle, 30A-33A

forcing screen orientation, 34Aforcing single task mode, 33A-34A

ListActivity, 43A-44AListFiles, 151A-152A, 154AMainActivity, 127AMenuScreen, 37A-38Amultiple activities

buttons, 36A-37Acreating activities with implicit

intents, 44A-46Aexplained, 35A-36Aimplementing list of choices,

43A-44Alaunching activities for results using

speed to text, 41A-43Alaunching activities from events,

37A-40A

passing primitive data typesbetween activities, 46A-49A

TextView, 36A-37AMultiTouch, 133A-135Amyanimation, 301A-302AMyBandRActivity, 297A-298AMyDB, 233A-234AMyDBhelper, 234A-235AMyLocation, 253A-255A,

256A-257A, 259A-260A,261A-262A, 265A-266A,269A-273A

MyMarkerLayer, 267A-268AMyPreferences, 223AOpenGlExample, 144A-145AOrientationMeasurements,

178A-179Apassing primitive data types between,

46A-49APhysicalKeyPress, 119A-121APlayGame, 38A-39A, 48A-49APressAndPlay, 54A-55AProgrammaticLayout, 91APyramid, 140A-141APyramidRenderer, 142A-144ARecognizerIntent, 41A-43AResponderService, 200A-203Arpc, 292A-294ArpcService, 289A-290Arunnable activities, creating, 55A-57Asaving and restoring activity

information, 34ASearchDialogExample, 128ASeekBarEx, 114A-115AShowMyButton, 282A-283AShowNotification, 77A-78ASimpleActivity, 25A, 68A-71ASimpleBroadcastReceiver, 71ASimpleService, 66A-67A

318A activities

Page 74: The Android Developer's Collection

SimpleService2, 71A-72ASimpleWidgetProvider, 73ASMSResponder, 198A-200ASpinnerExample, 111AStartScreen, 46A-47ATelephonyApp, 181A-182Atestfactorial, 311A-312ATouchExamples, 129ATwitterCookBook, 214A-215AUpdateAndList, 215A-219A

activity element, 29A

ActivityLifecycle, 32A-33A

ADB (Android Debug Bridge), 307A-313A

adb kill-server command, 307A

adb logcat command, 307A-309A

adb pull command, 18A

adb push command, 18A

adb shell bmgr backup command, 297A

adb shell bmgr restore command, 297A

adb shell bmgr run command, 298A

adb shell command, 18A

adb shell dumpsys command, 314A-315A

adb shell ps command, 313A

adb shell top command, 313A

adb start-server command, 307A

adb uninstall command, 18A

add() method, 121A

addOverlay() method, 267A

addOverlayItem() method, 269A

addresses

translating addresses to locations,261A-262A

translating locations to addresses,258A-260A

addSubMenu() method, 124A

AIDL (Android Interface DefinitionLanguage), 288A

AJAX (Google Asynchronous Javascript AndXML), 205A

AK8976A, 10A

AKM (Asahi Kasei Microsystems), 10A

AlertDialog class, 75A-76A

alerts

creating with AlertDialog class,75A-76A

creating with Toast, 74A-75Aproximity alerts, 274A-275Ashowing notifications in status bar,

76A-78A<alpha> attributes, 299A

alternate resources, specifying, 81A-82A

AMOLED (active-matrix organic LED displays), 8A

Android Debug Bridge (ADB), 18A,307A-313A

Android Interface Definition Language(AIDL), 288A

Android Market

alternatives to, 22Acharging for applications, 20A-21Adifferentiating applications, 20AEnd User License Agreement

(EULA), 19Aimproving application visibility,

19A-20Amanaging reviews and updates,

21A-22Aoverview, 19A

Android native components

developing, 284A-287Aexplained, 283A-284Atype mapping between Java and

Android native components, 285AAndroid OS 1.5, 15A

Android OS 1.6, 15A

Android OS 2.0, 16A

Android OS 2.0.1, 16A

Android OS 2.1, 16A

Android OS 2.2, 16A

319AAndroid OS 2.2

Page 75: The Android Developer's Collection

Android SDK, 16A-17A

ADB (Android Debug Bridge),307A-313A

Android Debug Bridge, 18Aemulator, 16A-17AHierarchy Viewer, 309A-313Ainstalling, 14A-15ALogCat, 307A-309Asigning and publishing, 18Asoftware features and API level,

15A-16Aupgrading, 14A-15A

Android smartphones

hardware differencesscreens, 8Asensors, 9A-10Auser input methods, 9A

HTC models, 6Amarking device’s current location

on map, 274AMotorola models, 6ASamsung models, 6Atable of, 3A

AndroidManifest.xml file, 28A-29A, 40A,68A, 152A-153A, 197A-198A, 211A, 224A,238A-239A, 246A-247A, 252A-253A,264A, 291A, 296A-297A

Android.mk file, 285A-286A

animated.xml file, 300A-301A

animation

creating, 299A-302Aframe-by-frame animation, 298ATween animation, 298A-299A

App Widgets

creating, 72A-74Aexplained, 11A, 72A

application element, 29A

applications

activities. See activitiesalerts

creating with AlertDialog class,75A-76A

creating with Toast, 74A-75Ashowing notifications in status bar,

76A-78Ain Android Market

charging for applications, 20A-21Adifferentiating, 20Aimproving application visibility,

19AAndroidManifest.xml file, 28A-30AApp Widgets. See App Widgetsautogenerated content, 26A-28Abroadcast receivers

explained, 69A-70Alifecycle, 70Astarting services based on

broadcasted events, 70A-72Aclasses. See classesdebugging

Android SDK debug tools,307A-313A

Android system debug tools,313A-316A

Eclipse built-in debug tools,303A-306A

GNU project DeBugger (GDB),315A-316A

overview, 303Adevelopment. See developmentmultimedia. See multimediaoverview, 23A-24Apackages, 28A-30Aprojects

creating, 24Adirectory structure, 26A-28Arenaming, 30A

320A Android SDK

Page 76: The Android Developer's Collection

renaming parts of, 30Athreads

canceling, 57A-58Acreating runnable activities,

55A-57Aexplained, 51A-52Ahandlers, 58A-64Alaunching secondary threads,

51A-55Asetting thread priorities, 57Asharing between two applications,

58AArchos, 7A

ArrayAdapter constructor, 112A

Asahi Kasei Microsystems (AKM), 10A

AsyncTask class, 209A

audio

adding media and updating paths,165A

choosing and playing back,154A-157A

explained, 154Amanipulating raw audio, 158A-163Arecording, 157A-158ASoundPool class, 163A-164A

AudioExamples activity, 155A-157A

AudioExamplesRaw activity, 161A-163A

AudioExamplesSP activity, 164A

AudioRecord instance, 158A-160A

autogenerated content, 26A-28A

automobiles, Roewe 350, 7A

autosending SMSs based on received SMSs,197A-203A

BBackgroundTimer activity, 60A-61A

backing up

files, 296Aruntime data, 294A-296A

Backup Manager

backing up files, 296Abacking up runtime data, 294A-296Atriggering backup and restore, 296A

BackupAgent, 294A-296A

BackupAgentHelper, 296A

BackupManager class, 294A-296A

bindService() function, 291A

BitmapFactory class, 148A

Bluetooth

accessing wireless networks,191A-193A

device vibration, 191Adiscovering Bluetooth devices, 187Aexplained, 185A-186Aopening Bluetooth sockets,

188A-191Apairing with bonded Bluetooth

devices, 188Aturning on, 186A-187A

BluetoothAdapter, 186A

BluetoothClass, 186A

BluetoothDevice, 186A

BluetoothServerSocket, 186A

BluetoothSocket, 186A

BMA150, 10A

boot image, 3A

bootloader, 3A

Bosch Sensortec, 10A

breakpoints, debugging through, 306A

broadcast receivers

explained, 69A-70Astarting services based on broadcasted

events, 70A-72Abroadcasted events, starting services based

on, 70A-72A

BroadcastReceiver, 196A

Browser database, 243A

321ABrowser database

Page 77: The Android Developer's Collection

browsers, customizing, 204A

BuildingMenus activity, 122A-124A

buttons

adding, 36A-37A, 102A-105Acustomizing, 277A-283Adefined, 101Aplaying ring-tone songs on button

press, 51A-55A

CCallBack interface, 172A

CallLog, 243A

camera

accessing, 169Acustomizing, 170A-175A

CameraApplication activity, 172A-175A

cameraoverlay.xml file, 170A-171A

canceling threads, 57A-58A

capacitive touchscreen technology, 9A

Capella Microsystems, Inc., 10A

capturing text from EditText objects, 101A

ChangeFont activity, 96A-97A

changing

text attributes, 95A-98AUI based on stored data, 225A-228A

charging for applications in Android Market,20A-21A

check boxes

creating, 105A-109Adefined, 101A

CheckBoxExample activity, 106A-107A

choosing audio files, 154A-157A

Chrome OS, 2A

ckbox.xml file, 105A-106A

classes, 186A

ActivityLifecycle, 32A-33AAlertDialog, 75A-76A

AsyncTask, 209AAudioExamples, 155A-157AAudioExamplesRaw, 161A-163AAudioExamplesSP, 164ABackgroundTimer, 60A-61ABackupAgent, 294A-296ABackupAgentHelper, 296ABackupManager, 294A-296ABitmapFactory, 148ABluetoothAdapter, 186ABluetoothClass, 186ABluetoothDevice, 186ABluetoothSocket, 186ABuildingMenus, 122A-124ACameraApplication, 172A-175AChangeFont, 96A-97ACheckBoxExample, 106A-107AConnectivityManager, 192A-193AConstants, 235ACountDownTimerExample, 61A-62ADataStorage, 224A, 226A-227ADataStorageTester, 247A-248ADiary, 237A-238ADiaryContentProvider, 245A-246ADisplayDiaries, 240A-242AEdgeDetection, 56A-57AEditText, 98A-101AEula, 228A-231AFlingExample, 131A-132AGeocoder, 258A-261AGestures, 139A-140AGoogleSearch, 206A-208AHandleMessage, 63A-64AHandlerUpdateUi, 93A-94A,

112A-114AHardwareTelephony, 184A-185AImageManipulation, 149A-150A

322A browsers, customizing

Page 78: The Android Developer's Collection

ItemizedOverlay, 267AListActivityExample, 44A-46AListFiles, 151A-152ALocationManager, 251AMainActivity, 127AMediaPlayer, 154A-157AMediaRecorder

playing audio, 154A-157Arecording audio, 157A-158A

MenuScreen, 37A-38AMultiTouch, 133A-135Amyanimation, 301A-302AMyBandRActivity, 297A-298AMyButton, 279A-282AMyDB, 233A-234AMyDBhelper, 234A-235AMyLocation, 253A-255A,

256A-257A, 259A-260A,261A-262A, 265A-266A,269A-273A

MyMarkerLayer, 267A-268AMyPreferences, 223AmyServiceConnection, 291AOpenGlExample, 144A-145AOrientationMeasurements,

178A-179APhysicalKeyPress, 119A-121APlayGame, 38A-39A, 48A-49APressAndPlay, 54A-55AProgrammaticLayout, 91APyramid, 140A-141APyramidRenderer, 142A-144AR, 27A-28Arenaming, 30AResponderService, 200A-203Arpc, 292A-294ArpcService, 289A-290ASearchDialogExample, 128A

SeekBarEx, 114A-115AShowMyButton, 282A-283AShowNotification, 77A-78ASimpleActivity, 68A-71ASimpleBroadcastReceiver, 71ASimpleOnGestureListener, 131ASimpleService, 66A-67ASimpleService2, 71A-72ASimpleWidgetProvider, 73ASmsManager, 195A-197ASMSResponder, 198A-200ASoundPool, 163A-164ASpinnerExample, 111AStartScreen, 46A-47ATelephonyApp, 181A-182ATelephonyManager, 181A-182Atestfactorial, 311A-312ATouchExamples, 129ATwitterCookBook, 214A-215AUpdateAndList, 215A-219AVibrator, 191AWebSettings, 204A

Clinton, DeWitt, 210A

close() method, 232A

CM3602, 10A

Color attribute, 80A

colors.xml file, 97A

commands

adb kill-server, 307Aadb logcat, 307A-309Aadb pull, 18Aadb push, 18Aadb shell, 18Aadb shell bmgr backup, 297Aadb shell bmgr restore, 297Aadb shell bmgr run, 298Aadb shell dumpsys, 314A-315A

323Acommands

Page 79: The Android Developer's Collection

adb shell ps, 313Aadb shell top, 313Aadb start-server, 307Aadb uninstall, 18A

comments, 12A

compare() method, 150A

configuring Google Maps, 263A-265A

Confirm Perspective Switch dialog box, 306A

ConnectivityManager class, 192A-193A

Constants class, 235A

Contacts database, 243A-244A

content providers

accessing, 244Acreating, 244A-249Anative databases available as content

providers, 243A-244AURIs (uniform resource identifiers),

244AcontentResolver instance, 244A

cookbook.c, 284A

countdown timer, 61A-62A

CountDownTimerExample activity, 61A-62A

createFromPdu() method, 200A

createItem() method, 267A

createRfcommSocketToServiceRecord()method, 190A

createScaledBitmap() method, 149A

Criteria class, 252A

Cupcake, 15A

customizing

buttons, 277A-283Acamera, 170A-175Aviews, 277A-283Aweb browsers, 204A

DDalvik Debug Monitoring Service (DDMS),

304A-306A

data image, 3A

data storage

content providersaccessing, 244Acreating, 244A-249Anative databases available as content

providers, 243A-244AURIs (uniform resource identi-

fiers), 244Aexplained, 221Afile saving and loading, 249A-250Ashared preferences

changing UI based on stored data,225A-228A

creating and retrieving, 222AEnd User License Agreement

(EULA), 228A-232Aexplained, 221Apreferences framework, 222A-225A

SQLite databasecreating personal diaries,

239A-242Acreating separate database package,

232A-235Aexplained, 232Autilizing separate database packages,

236A-239Adata types, passing between activities,

46A-49A

databases

Browser, 243ACallLog, 243AContacts, 243A-244ALiveFolders, 244AMediaStore, 244A

324A commands

Page 80: The Android Developer's Collection

native databases available as contentproviders, 243A-244A

SearchRecentSuggestions, 244ASetting, 244ASQLite. See SQLite databaseSyncStateContract, 244AUserDictionary, 244A

DataStorage activity, 224A, 226A-227A

DataStorageTester activity, 247A-248A

DDMS (Dalvik Debug Monitoring Service),304A-306A

debugging

Android Debug Bridge, 18AAndroid SDK debug tools

ADB (Android Debug Bridge),307A

Hierarchy Viewer, 309A-313ALogCat, 307A-309A

Android system debug tools,313A-316A

Eclipse built-in debug toolsDalvik Debug Monitoring Service

(DDMS), 304A-306Adebugging through breakpoints,

306Aspecifying run configuration,

303A-304AGNU project DeBugger (GDB),

315A-316Aoverview, 303A

declaring permissions, 287A-288A

delete() method, 245A

design, 12A-13A

detectEdges() function, 55A

development

Android native components,284A-287A

Android SDKAndroid Debug Bridge, 18Aemulator, 16A-17A

installing, 14A-15Asigning and publishing, 18Aupgrading, 14A-15A

Android smartphones, software fea-tures and API level, 15A-16A

coding styles, 11A-12Adesign, 12A-13Aforward compatibility, 13Arobustness, 13A-14A

Device Status panel (DDMS), 305A

Devices panel (DDMS), 305A

devices running Android

automobiles, 7ABluetooth devices

accessing wireless networks,191A-193A

device vibration, 191Adiscovering, 187Aopening Bluetooth sockets,

188A-191Apairing with bonded Bluetooth

devices, 188Ahardware differences

screens, 8Asensors, 9A-10Auser input methods, 9A

HTC models, 6Amarking device’s current location on

map, 274AMotorola models, 6Areturning device’s rotational attitude,

176A-179ASamsung models, 6Atable of, 3A-5Atablets, 7A

dialing phone numbers, 185A

dialog boxes. See specific dialog boxes

325Adialog boxes

Page 81: The Android Developer's Collection

diaries.xml file, 239A

diary, creating, 239A-242A

Diary activity, 237A-238A

DiaryContentProvider activity, 245A-246A

diaryrow.xml file, 239A-240A

diary.xml file, 236A

dichotomy of Android, 2A

differentiating applications in AndroidMarket, 20A

Dimension attribute, 80A

dimens.xml file, 97A

directories

directory structure of projects,26A-28A

resource directories, 79Adiscovering Bluetooth devices, 187A

DisplayDiaries activity, 240A-242A

divideMessage() method, 197A, 200A

Donut, 15A

D-pad, 9A

draw() method, 142A

drawArcs() method, 278A

drawing 3D images, 140A-145A

Droid (Motorola), 6A

Droid Incredible (HTC), 6A

Droid X (Motorola), 6A

drop-down menus, creating, 110A-112A

dumpsys, 314A-315A

EEclair, 16A

Eclipse, 12A

debug toolsDalvik Debug Monitoring Service

(DDMS), 304A-306Adebugging through breakpoints,

306A

specifying run configuration,303A-304A

layouts, building in Eclipse Editor,83A-85A

EdgeDetection activity, 56A-57A

EditText class, 98A-101A

elements

activity, 29Aapplication, 29Aintent-filter, 29Apermission, 287A-288A

emulator, 12A, 16A-17A

Emulator Control (DDMS), 305A

enableCompass() method, 274A

enabled providers, listing, 256A-258A

enableMyLocation() method, 274A

End User License Agreement (EULA),19A, 228A-232A

enforcing permissions, 287A-288A

EULA (End User License Agreement), 19A,228A-232A

Eula activity, 228A-231A

event handlers

building menus, 121A-125Adefining menus in XML, 126A-127Aexplained, 117Aintercepting physical key presses,

117A-121Alistening for fling gestures, 130A-132Amultitouch, 133A-136Areacting to touch events, 128A-130Autilizing SEARCH key, 127A

event listeners

building menus, 121A-125Adefining menus in XML, 126A-127Aexplained, 117Aintercepting physical key presses,

117A-121A

326A diaries.xml file

Page 82: The Android Developer's Collection

listening for fling gestures, 130A-132Amultitouch, 133A-136Areacting to touch events, 128A-130Autilizing SEARCH key, 127A

events

ACTION_DOWN, 133AACTION_MOVE, 133AACTION_POINTER_DOWN,

133AACTION_POINTER_UP, 133AACTION_UP, 133Abroadcasted events, starting services

based on, 70A-72Alaunching activities from, 37A-40Aphone state listener events, 183Atouch events, reacting to, 128A-130A

evolution of Android, 1A-2A

extending BackupAgentHelper, 296A

Ffactorial() method, 285A, 291A, 312A

file_row.xml file, 152A

files. See also specific files

audio files. See audioautogenerated content, 26A-28Abacking up, 296AJava files, referencing resources from,

28Asaving and loading, 249A-250AXML files, referencing resources from,

28Afling gestures, listening for, 130A-132A

FlingExample activity, 131A-132A

forcing

screen orientation, 34Asingle task mode, 33A-34A

forms, creating, 100A-101A

forward compatibility, 13A

frame-by-frame animation, 298A

FroYo, 16A

functions. See specific functions

GGalaxy S (Samsung), 6A

Galaxy Tab, 7A

game.xml file, 39A

GDB (GNU project DeBugger), 315A-316A

Geocoder class, 258A-261A

geocoding, 261A-262A

gestures, 11A

fling gestures, listening for,130A-132A

Gesture Builder application, 137AGestures activity, 139A-140Alibraries, 136A-138A

getActiveNetworkInfo() method, 192A

getCount() method, 240A

getDefault() method, 195A

getDefaultAdapter() method, 186A

getdiaries() method, 233A

getFromLocationName() method, 261A

getHomeTimeline() method, 215A

getIntExtra method, 48A

getItem() method, 240A

getItemID() method, 240A

getLastKnownLocation() method, 253A

getMyLocation() method, 274A

getNetworkInfo() method, 192A

getOrientation() method, 177A, 274A

getOriginatingAddress() method, 200A

getOverlays() method, 269A

getPixel() method, 148A

getPreferences() method, 222A

getProvider() method, 252A

327AgetProvider() method

Page 83: The Android Developer's Collection

getRotationMatrix() method, 176A

getSensorList() method, 176A

getSharedPreferences() method, 222A

getStringExtra method, 48A

getType() method, 245A

getView() method, 240A

Gist, Inc., 210A

GNU project DeBugger (GDB), 315A-316A

Google Android Market. See Android Market

Google Asynchronous Javascript And XML(AJAX), 205A

Google Maps

adding markers on maps, 267A-271Aadding to applications, 265A-266Aadding views to maps, 271A-274Aconfiguring, 263A-265AMaps API key, 263Amarking device’s current location on

map, 274Asetting up proximity alerts,

274A-275AGoogle TV, 8A

GoogleSearch activity, 206A-208A

Graphviz Dot utility, 313A

HHandleMessage activity, 63A-64A

handleMessage() method, 63A

handlers

countdown timers, 61A-62Aexplained, 58Ahandling time-consuming

initializations, 62A-64Ascheduling runnable tasks from main

thread, 59A-61AHandlerUpdateUi activity, 93A-94A,

112A-114A

hard keyboards, 11A

hardware differences

screens, 8Asensors, 9A-10Auser input methods, 9A

hardware interfaces

Bluetoothaccessing wireless networks,

191A-193Adevice vibration, 191Adiscovering Bluetooth devices,

187Aexplained, 185A-186Aopening Bluetooth sockets,

188A-191Apairing with bonded Bluetooth

devices, 188Aturning on, 186A-187A

cameraaccessing, 169Acustomizing, 170A-175A

sensorsreturning device’s rotational

attitude, 176A-179Asensors accessible from Android

SDK, 176Atemperature and light sensors,

179A-180Atelephony

dialing phone numbers, 185Alistening for phone states,

183A-185ATelephonyManager class,

181A-182AHardwareTelephony activities, 184A-185A

height of UI elements, controlling, 86A-88A

Hierarchy Viewer, 309A-311A

history of Android, 1A-2A

HTC Dream, 6A

HTC EVO 4G, 10A

328A getRotationMatrix() method

Page 84: The Android Developer's Collection

HTC smartphones, 6A

HTTP GET, 204A-208A

HTTP POST, 209A

Hummingbird processor, 6A

IIAdditionalService.aidl, 289A

IAdditionService instance, 291A

ibutton.xml file, 103A-105A

image buttons, adding to table layouts,102A-105A

ImageManipulation activity, 149A-150A

images

Android images, 3Aanimation

creating, 299A-302Aframe-by-frame animation, 298ATween animation, 298A-299A

BitmapFactory class, 148Aloading for manipulation, 148A-153A

implicit intents

ACTION_CALL implicit intent,185A

ACTION_DIALER implicit intent,185A

launching activities with, 44A-46Ainitializations, handling time-consuming ini-

tializations, 62A-64A

initializeArrays() function, 63A

initService() method, 291A

insert() method, 245A

insertdiary() method, 232A

installing Android SDK, 14A-15A

integrating with Twitter, 210A

AndroidManifest.xml file, 211Alogin.xml file, 211A-212Amain.xml file, 211A-212Ausertimelinerow.xml file, 213A

intent-filter element, 29A

intercepting physical key presses,117A-121A

interfaces

CallBack, 172ALocationListener, 254A-256AOnClickListener, 130AOnGestureListener, 130ASharedPreferences. See shared prefer-

encesinter-process communication (IPC),

288A-294A

IPC (inter-process communication), 58A,288A-294A

isRouteDisplayed() method, 265A

ItemizedOverlay class, 267A

JJava

Java libraries, lack of support for, 2AJava Native Interface (JNI), 285AJava Virtual Machine (JVM), 285Areferencing resources from, 28Atype mapping between Java and

Android native components, 285Ajava-twitter, 210A

jint type, 285A

JNI (Java Native Interface), 285A

JNIEnv pointer, 285A

jobject pointer, 285A

jtwitter, 210A

JVM (Java Virtual Machine), 285A

Kkey presses, intercepting, 117A-121A

keyboards, 11A

keytool command, 263A

329Akeytool command

Page 85: The Android Developer's Collection

Llandscape mode, forcing, 34A

last location, retrieving, 253A-254A

launching

activities from events, 37A-40Aactivities with implicit intents, 44Asecondary threads, 51A-55Aservices based on broadcasted events,

70A-72ALayout View (Hierarchy Viewer), 310A-311A

layouts

building in Eclipse Editor, 83A-85Acontrolling width and height of UI

elements, 86A-88Adeclaring programmatically, 90A-91Asetting relative layout and layout ID,

89A-90Aupdating from separate threads,

92A-94Awidgets. See widgets

LBS (Location-Based Services)

explained, 251AGoogle Maps

adding markers on maps,267A-271A

adding to applications, 265A-266Aadding views to maps, 271A-274Aconfiguring, 263A-265AMaps API key, 263Amarking device’s current location

on map, 274Asetting up proximity alerts,

274A-275Alisting enabled providers, 256A-258ALocation class, 251ALocationListener, 251ALocationManager, 251Aretrieving last location, 253A-254A

translating addresses to locations,261A-262A

translating locations to addresses,258A-260A

updating location upon change,254A-256A

LCD (liquid crystal displays), 8A

LED (light-emitting diodes), 8A

libraries

gesture libraries, 136A-138AOpen Graphics Library for Embedded

Systems (OpenGL ES), 140A-145Alicense agreements

adding, 228A-232AAndroid Market, 19A

lifecycle

of activities, 30A-33Aforcing screen orientation, 34Aforcing single task mode, 33A-34Asaving and restoring activity infor-

mation, 34A-35Aof broadcast receivers, 70Aof services, 64A-65A

light sensors, 179A-180A

light-emitting diodes (LED), 8A

Linux utilities, lack of support for, 2A

liquid crystal displays (LCD), 8A

LIS331DLH, 10A

ListActivity, 43A-44A

ListActivityExample, 44A-46A

listenUsingRfcommWithServiceRecord()method, 188A

ListFiles activity, 151A-152A, 154A

listing enabled providers, 256A-258A

lists, implementing, 43A-44A

LiveFolders database, 244A

LM3530, 10A

330A landscape mode, forcing

Page 86: The Android Developer's Collection

loading

files, 249A-250Aimages, 148A-153A

loading.xml file, 63A

loadLibrary() method, 286A

loadURL() method, 204A

Location class, 251A

Location Control (DDMS), 305A

Location-Based Services. See LBS (Location-Based Services)

LocationListener, 251A

LocationListener interface, 254A-256A

LocationManager, 251A

locations. See LBS (Location-Based Services)

LogCat, 305A, 307A-309A

Mmagnetometers, 9A

MainActivity activity, 127A

makefiles, 285A-286A

manipulating raw audio, 158A-163A

Maps API key, 263A

markers, adding to Google Maps,267A-271A

measureHeight() method, 278A

measureWidth() method, 278A

MediaPlayer, 154A-157A

MediaRecorder

playing audio, 154A-157Arecording audio, 157A-158A

MediaStore database, 244A

menus

building, 121A-125Adefining in XML, 126A-127Adrop-down menus, creating,

110A-112AMenuScreen activity, 37A-38A

methods. See specific methods

MODE_PRIVATE, 222A

MODE_WORLD_READABLE, 222A

MODE_WORLD_WRITEABLE, 222A

Moment (Samsung), 6A

Motorola app market, 22A

Motorola smartphones, 6A

multimedia

audioadding media and updating paths,

165Achoosing and playing back,

154A-157Aexplained, 154Amanipulating raw audio,

158A-163Arecording, 157A-158ASoundPool class, 163A-164A

imagesBitmapFactory class, 148Aloading for manipulation,

148A-153Asupported media types, 147A-148Avideo, 165A-167A

playing, 166A-167Arecording, 166A

multiple activities

buttons, 36A-37Aexplained, 35A-36Aimplementing list of choices, 43A-44Alaunching activities for results using

speed to text, 41A-43Alaunching activities from events,

37A-40Alaunching activities with implicit

intents, 44A-46Apassing primitive data types between

activities, 46A-49ATextView, 36A-37A

331Amultiple activities

Page 87: The Android Developer's Collection

multiprocessing, 11A

multitouch, 11A, 133A-136A

MultiTouch activity, 133A-135A

music ring-tones, playing on button press,51A-55A

my_search.xml file, 127A

myanimation activity, 301A-302A

MyBandRActivity, 297A-298A

MyButton class, 279A-282A

MyDB activity, 233A-234A

MyDB() method, 232A

MyDBhelper activity, 234A-235A

MyLocation activity, 253A-255A, 256A-257A,259A-260A, 261A-262A, 265A-266A,269A-273A

MyMarkerLayer activity, 267A-268A

MyPreferences activity, 223A

myServiceConnection class, 291A

Nnative components

developing, 284A-287Aexplained, 283A-284A

native databases available as contentproviders, 285A

ndk.java, 286A

networking

integrating with Twitter, 210AAndroidManifest.xml file, 211Alogin.xml file, 211A-212Amain.xml file, 212A-213Ausertimelinerow.xml file, 213A

SMS (short message service)autosending SMSs based on

received SMSs, 197A-203Asending SMSs through

SmsManager, 195A-197A

web contentcustomizing web browsers, 204AHTTP GET, 204A-208AHTTP POST, 209A

wireless networks, accessing,191A-193A

New Android Project screen, 24A

Nexus One, 6A

notifications, showing in status bar, 76A-78A

Oobjects. See classes

onActivityResult() function, 41A

onBackPressed() method, 119A

onBackup() method, 295A

onBind() method, 66A

OnClickListener interface, 130A

onCreate() method, 24A, 245A

onCreateContextMenu() method, 124A

onCreateOptionsMenu() method, 121A

onDestroy() method, 65A

onDown() method, 131A

onDraw() method, 278A

onDrawFrame() method, 142A, 144A

onFling() method, 131A

onFocusChanged() method, 118A

OnGestureListener interface, 130A

onGesturePerformed() method, 137A

onKeyDown() method, 118A

onKeyLongPress() method, 118A

onKeyUp() method, 118A

onLocationChanged() method, 254A

onLongPress() method, 131A

onMeasure() method, 277A, 278A

onPrepareOptionsMenu() method, 121A

332A multiprocessing

Page 88: The Android Developer's Collection

onRestore() method, 295A

onRestoreInstanceState() function, 34A

onSaveInstanceState() function, 34A

onScroll() method, 131A

onSearchRequested() method, 127A

onSensorChanged() method, 179A

onServiceDisconnected function, 291A

onShowPress() method, 131A

onSingleTapUp() method, 131A

onSurfaceChanged() method, 142A

onSurfaceCreated() method, 142A

onTap() method, 267A

onTick() method, 61A

onTouch() method, 133A

onTouchEvent() method, 118A, 130A

OnTouchListener, 133A

onTrackballEvent() method, 118A

Open Graphics Library for EmbeddedSystems (OpenGL ES), 140A-145A

Open Handset Alliance, 1A

open() method, 232A

OpenGL ES (Open Graphics Library forEmbedded Systems), 140A-145A

OpenGlExample activity, 144A-145A

opening Bluetooth sockets, 188A-191A

Opto Semiconductor, 10A

orientation of screen, forcing, 34A

OrientationMeasurements activity,178A-179A

Ppackages

explained, 28A-30Arenaming, 30A

pairing with bonded Bluetooth devices, 188A

passing primitive data types between activities, 46A-49A

paths, updating, 165A

pauseMP() method, 155A

permission element, 287A-288A

permissions

ACCESS_COARSE_LOCATIONpermission, 252A

ACCESS_FINE_LOCATION permission, 252A

declaring and enforcing, 287A-288Apersonal diary, creating, 239A-242A

phone numbers, dialing, 185A

phone states, listening for, 183A-185A

PhoneStateListener class, 183A-185A

PhysicalKeyPress activity, 119A-121A

PictureCallback() method, 171A

play_music() function, 51A

PlayGame activity, 38A-39A, 48A-49A

playing

audio, 154A-157Aring-tone songs on button press,

51A-55Avideo, 166A-167A

populate() method, 269A

portrait mode, forcing, 34A

preferences, shared. See shared preferences

preferences framework, 222A-225A

preferences.xml file, 223A

PressAndPlay activity, 54A-55A

primitive data types, passing between activities, 46A-49A

priorities, setting, 57A

ProcessResponse() method, 206A

Profile Panel (Hierarchy Viewer), 312A

ProgrammaticLayout activity, 91A

progress bars

creating, 112A-114Adefined, 101A

333Aprogress bars

Page 89: The Android Developer's Collection

projects

creating, 24Adirectory structure, 26A-28Arenaming, 30A

Properties View (Hierarchy Viewer),310A-311A

protectionLevel attribute, 288A

proximity alerts, setting up, 274A-275A

ps command, 313A

publishing, 18A

put() method, 222A

Pyramid activity, 140A-141A

PyramidRenderer activity, 142A-144A

Q-Rquery() method, 245A

radio buttons

creating, 108A-110Adefined, 101A

radio image, 3A

raw audio, manipulating, 158A-163A

rbutton.xml file, 109A

reacting to touch events, 128A-130A

RecognizerIntent activity, 41A-43A

recording

audio, 157A-158Avideo, 166A

recovery image, 3A

registerForContextMenu() function, 124A

registering audio files, 165A

registerReceiver() method, 70A

relative layout, setting, 89A-90A

RelativeLayout view, 89A-90A

releaseService() method, 291A

remote procedure calls (RPCs),implementing, 289A-294A

renaming

classes, 30Apackages, 30Aprojects, 30A

Representational State Transfer (REST),205A

requestLocationUpdates() method, 254A

requestRestore() method, 297A

res/anim/ directory, 79A

res/drawable/ directory, 79A

resistive touchscreen technology, 9A

res/layout/ directory, 79A

resource directories

list of, 79Aspecifying alterate resources, 81A-82A

ResponderService activity, 200A-203A

res/raw/ directory, 79A

REST ( Representational State Transfer),205A

restoring activity information, 34A

res/values/ directory, 79A

res/xml/ directory, 79A

retrieving

last location, 253A-254Ashared preferences, 222A

returning device’s rotational attitude,176A-179A

reverse geocoding, 258A-260A

reviews in Android Market, 21A-22A

RFCOMM, 188A

ring-tone songs, playing on button press,51A-55A

ring-tone text transfer language (RTTTL), 53A

R.java class, 27A-28A

robustness, 13A-14A

Roewe 350, 7A

<rotate> attributes, 299A

rotational attitude, returning, 176A-179A

334A projects

Page 90: The Android Developer's Collection

rpc activity, 292A-294A

RPCs (remote procedure calls),mplementing, 289A-294A

rpcService activity, 289A-290A

run configuration, specifying, 303A-304A

runnable activities, creating, 55A-57A

runnable tasks from main thread,scheduling, 59A-61A

runtime data, backing up, 294A-296A

SSamsung smartphones, 6A

saving

activity information, 34Afiles, 249A-250A

<scale> attributes, 299A

scheduling runnable tasks from mainthread, 59A-61A

screen orientation, forcing, 34A

screens, 8A

SEARCH KEY, utilizing, 127A

SearchDialogExample activity, 128A

SearchRecentSuggestions database, 244A

secondary threads, launching, 51A-55A

security, 287A-288A

seek bars

creating, 114A-116Adefined, 102A

SeekBarEx activity, 114A-115A

self-contained services, creating, 65A-69A

sending SMSs through SmsManager,195A-197A

sendMuiltTextMessage() method, 200A

sendMultipartTextMessage() method, 197A

sendTextMesssage() method, 195A

SENSOR_DELAY_FASTEST, 178A

SENSOR_DELAY_GAME, 178A

SENSOR_DELAY_UI, 178A

SensorEventListener, 178A

sensors, 9A-10A

returning device’s rotational attitude,176A-179A

sensors accessible from Android SDK, 176A

temperature and light sensors,179A-180A

separate database packages

creating, 232A-235Autilizing, 236A-239A

services

creating, 65A-69Aexplained, 64Alifecycle, 64A-65Astopping, 65A

setBuiltInZoomControls() method, 269A

setContentView() function, 25A

setDaemon() method, 57A

setGravity() method, 75A

setIcon() method, 121A

setListAdapter() function, 43A

setMeasuredDimension() method, 277A

setOnItemClickListener() function, 43A-44A

setPixel() method, 148A

setPriority() function, 57A

setRequestMethod() method, 209A

setText() method, 278A

setTextColor() method, 278A

setTextSize() method, 278A

Setting database, 244A

SFH7743A, 10A

Shanghai Automotive Industry Corporation, 7A

shared preferences

changing UI based on stored data,225A-228A

creating and retrieving, 222A

335Ashared preferences

Page 91: The Android Developer's Collection

End User License Agreement(EULA), 228A-232A

explained, 221Apreferences framework, 222A-225A

SharedPreferences interface. See sharedpreferences

sharing threads between two applications, 58A

ShowMyButton activity, 282A-283A

ShowNotification activity, 77A-78A

ShutterCallback() method, 171A

signing, 18A

SimpleActivity activity, 68A-71A

SimpleBroadcastReceiver activity, 71A

SimpleOnGestureListener class, 131A

SimpleService activity, 66A-67A

SimpleService2 activity, 71A-72A

SimpleWidgetProvider activity, 73A

single task mode, forcing, 33A-34A

size() method, 267A

sleep() method, 55A

smartphones running Android

hardware differencesscreens, 8Asensors, 9A-10Auser input methods, 9A

HTC models, 6Amarking device’s current location on

map, 274AMotorola models, 6ASamsung models, 6Atable of, 3A-5A

SMS (short message service)

autosending SMSs based on receivedSMSs, 197A-203A

sending SMSs through SmsManager,195A-197A

SmsManager class, 195A-197A

SMSResponder activity, 198A-200A

sockets (Bluetooth), opening, 188A-191A

soft keyboards, 11A

sort() method, 151A

SoundPool class, 163A-164A

speech to text, launching activities forresults using speed to text, 41A-43A

spinner_entry.xml file, 110A-111A

SpinnerExample activity, 111A

spinners, 101A

spinner.xml file, 110A

SQLite database

creating personal diaries, 239A-242Acreating separate database package,

232A-235Aexplained, 232Autilizing separate database packages,

236A-239AST Microelectronics, LIS331DLH, 10A

startdiscovery() method, 187A

starting. See launching

startMethodTracing() function, 312A

startMP() method, 155A

StartScreen activity, 46A-47A

startTracking() method, 119A

status bar, showing notifications in, 76A-78A

stop() method, 57A

stopMethodTracing() method, 312A

stopping services, 65A

storage. See data storage

Streak, 7A

String attribute, 80A

strings, 12A

strings.xml file, 40A

supported media types, 147A-148A

surface acoustic wave touchscreen technology, 9A

surfaceChanged() method, 172A

surfaceCreated() method, 172A

surfaceDestroyed() method, 172A

336A shared preferences

Page 92: The Android Developer's Collection

SyncStateContract database, 244A

system image, 3A

Ttables, adding image buttons to, 102A-105A

tablets, table of, 7A

takePicture() method, 171A

tasks, scheduling runnable tasks from mainthread, 59A-61A

telephony

dialing phone numbers, 185Alistening for phone states, 183A-185ATelephonyManager class, 181A-182A

Telephony Actions control (DDMS), 305A

Telephony Status control (DDMS), 305A

TelephonyApp activity, 181A-182A

TelephonyManager class, 181A-182A

television, Google TV, 8A

temperature sensors, 9A, 179A-180A

testfactorial activity, 311A-312A

text entry, 98A-100A

text manipulation

creating forms, 100A-101Aproviding text entry, 98A-100Asetting and changing text attributes,

95A-98ATextView attributes, 94A-95A

TextView, 36A-37A, 94A-95A

TFT (thin-film transistor) LCDs, 8A

threads

canceling, 57A-58Acreating runnable activities, 55A-57Aexplained, 51A-52Ahandlers

countdown timers, 61A-62Aexplained, 58Ahandling time-consuming initial-

izations, 62A-64A

scheduling runnable tasks frommain thread, 59A-61A

launching secondary threads, 51A-55Asetting thread priorities, 57Asharing between two applications, 58Aupdating layouts from separate threads,

92A-94Atime-consuming initializations, handling,

62A-64A

Timeline Panel (Hierarchy Viewer), 312A

timers

background timer, 60A-61Acountdown timer, 61A-62A

Toast, creating alerts with, 74A-75A

top command, 313A

touch events, reacting to, 128A-130A

TouchExamples activity, 129A

touchscreen technology, 9A, 11A. See alsoUI techniques

listening for fling gestures, 130A-132Amultitouch, 133A-136Areacting to touch events, 128A-130A

TraceView, 311A-313A

trackballs, 9A

trackpad, 9A

<translate> attributes, 299A

translating

addresses to locations, 261A-262Alocations to addresses, 258A-260A

Tree View (Hierarchy Viewer), 310A-311A

TRTTTL (ring-tone text transfer language),53A

turning on Bluetooth, 186A-187A

Tween animation, 298A-299A

Twitter, integrating with, 210A

AndroidManifest.xml file, 211Alogin.xml file, 211A-212Amain.xml file, 211A-212Ausertimelinerow.xml file, 213A

337ATwitter, integrating with

Page 93: The Android Developer's Collection

Twitter Client, 210A

Twitter4J, 210A

TwitterCookBook activity, 214A-215A

type mapping between Java and Androidnative components, 285A

UUI techniques

3D images, drawing, 140A-145Abuttons

adding, 36A-37Aadding to table layouts, 102A-105Adefined, 101A

check boxescreating, 105A-109Adefined, 101A

controlling width and height of UIelements, 86A-88A

drop-down menus, creating,110A-112A

event handlers/event listenersbuilding menus, 121A-125Adefining menus in XML,

126A-127Aexplained, 117Aintercepting physical key presses,

117A-121Alistening for fling gestures,

130A-132Amultitouch, 133A-136Areacting to touch events,

128A-130Autilizing SEARCH key, 127A

layoutsbuilding in Eclipse Editor,

83A-85Adeclaring programmatically,

90A-91Asetting relative layout and layout

ID, 89A-90A

updating from separate threads,92A-94A

progress barscreating, 112A-114Adefined, 101A

radio buttonscreating, 108A-110Adefined, 101A

resource directorieslist of, 79Aspecifying alterate resources,

81A-82Aseek bars

creating, 114A-116Adefined, 102A

spinners, 101Atext manipulation

creating forms, 100A-101Aproviding text entry, 98A-100Asetting and changing text

attributes, 95A-98ATextView attributes, 94A-95A

TextView, 36A-37AUI attributes, 80AUI libraries

gesture libraries, 136A-138AOpen Graphics Library for

Embedded Systems (OpenGLES), 140A-145A

ViewGroups, 82Aviews

explained, 82ARelativeLayout, 89A-90A

uniform resource identifiers (URIs), 44A

Uniform Resource Identifiers (URIs), 244A

update() method, 245A

UpdateAndList activity, 215A-219A

updates, managing in Android Market,21A-22A

338A Twitter Client

Page 94: The Android Developer's Collection

updating

layouts from separate threads,92A-94A

location upon change, 254A-256Apaths, 165A

upgrading Android SDK, 14A-15A

URIs (uniform resource identifiers), 44A,244A

user input methods, 9A

UserDictionary, 244A

usertimelinerow.xml file, 213A

Vvibrate() method, 191A

vibration

Bluetooth devices, 191Avibration-pause sequences, 191A

Vibrator class, 191A

video, 165A-167A

playing, 166A-167Arecording, 166A

ViewGroups, 82A

views

adding to Google Maps, 271A-274Acustom views, 277A-283Aexplained, 82ARelativeLayout, 89A-90ATextView. See TextViewWebView object, 204A

Wweb browsers, customizing, 204A

web content

customizing web browsers, 204AHTTP GET, 204A-208AHTTP POST, 209A

WebSettings class, 204A

WebView object, 204A

widget_info.xml file, 74A

widget_layout.xml file, 74A

widgets

App Widgets. See App Widgetsbuttons

adding to table layouts, 102A-105Adefined, 101A

check boxescreating, 105A-109Adefined, 101A

drop-down menus, creating,110A-112A

progress barscreating, 112A-114Adefined, 101A

radio buttonscreating, 108A-110Adefined, 101A

seek barscreating, 114A-116Adefined, 102A

spinners, 101Awidth of UI elements, controlling, 86A-88A

Winterstein, Daniel, 210A

Wire-frame View (Hierarchy Viewer),310A-311A

wireless networks, accessing, 191A-193A

X-Y-ZXML files

AndroidManifest.xml file, 28A-30Adefining menus in XML, 126A-127Areferencing resources from, 28A

Yamamoto, Yusuke, 210A

339AYamamoto, Yusuke

Page 95: The Android Developer's Collection

This page intentionally left blank

Page 96: The Android Developer's Collection

Android™

WirelessApplication

DevelopmentSecond Edition

Page 97: The Android Developer's Collection

This page intentionally left blank

Page 98: The Android Developer's Collection

Android™

WirelessApplication

DevelopmentSecond Edition

Shane ConderLauren Darcey

Upper Saddle River, NJ • Boston • Indianapolis • San FranciscoNew York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

Page 99: The Android Developer's Collection

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and the publish-er was aware of a trademark claim, the designations have been printed with initial capitalletters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors or omis-sions. No liability is assumed for incidental or consequential damages in connection with orarising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk pur-chases or special sales, which may include electronic versions and/or custom covers andcontent particular to your business, training goals, marketing focus, and branding interests.For more information, please contact:

U.S. Corporate and Government Sales(800) [email protected]

For sales outside the United States please contact:

International [email protected]

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data:Conder, Shane, 1975-

Android wireless application development / Shane Conder, Lauren Darcey. — 1st ed.

p. cm.

ISBN 978-0-321-74301-5 (pbk. : alk. paper) 1. Application software—Development. 2.Android (Electronic resource) 3. Mobile computing. I. Darcey, Lauren, 1977- II. Title.

QA76.76.A65C6637 2011

005.1—dc22

2010046618

Copyright © 2011 Shane Conder and Lauren Darcey

All rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibited repro-duction, storage in a retrieval system, or transmission in any form or by any means, elec-tronic, mechanical, photocopying, recording, or likewise. For information regarding permis-sions, write to:

Pearson Education, IncRights and Contracts Department501 Boylston Street, Suite 900Boston, MA 02116Fax: (617) 671-3447

Android is the trademark of Google, Inc. Pearson Education does not assert any right to theuse of the Android trademark and neither Google nor any other third party having any claimin the Android trademark have sponsored or are affiliated with the creation and develop-ment of this book.

Some figures that appear in this book have been reproduced from or are modificationsbased on work created and shared by the Android Open Source Project and used accordingto terms described in the Creative Commons 2.5 Attribution License (http://creativecom-mons.org/licenses/by/2.5/).

ISBN-13: 978-0-321-74301-5ISBN-10: 0-321-74301-6

Text printed in the United States on recycled paper at Edwards Brothers, Ann Arbor,Michigan

Second Printing: March 2011

Editor-in-ChiefMark Taub

Acquisitions EditorTrina MacDonald

DevelopmentEditorSonglin Qiu

Managing EditorSandra Schroeder

Senior ProjectEditorTonya Simpson

Copy EditorCharlotte Kughen

IndexerHeather McNeill

ProofreaderWater CrestPublishing

TechnicalReviewersCharles Stearns

Douglas Jones

PublishingCoordinatorOlivia Basegio

Book DesignerGary Adair

CompositorMark Shirar

Page 100: The Android Developer's Collection

This book is dedicated to Bit, Nibble, Stack, Queue,Heap, and Null.

Page 101: The Android Developer's Collection

AcknowledgmentsThis book would never have been written without the guidance and encouragement wereceived from a number of supportive individuals, including our editorial team, cowork-ers, friends, and family.We’d like to thank the Android developer community, Google,and the Open Handset Alliance for their vision and expertise.Throughout this project,our editorial team at Pearson Education (Addison-Wesley) always had the right mix ofprofessionalism and encouragement.Thanks especially to Trina MacDonald, OliviaBasegio, Songlin Qiu, and our crack team of technical reviewers: Doug Jones andCharles Stearns (as well as Dan Galpin,Tony Hillerson, and Ronan Schwarz, whoreviewed the first edition). Dan Galpin also graciously provided the clever Androidgraphics used for Tips, Notes, and Warnings.We’d also like to thank Ray Rischpater forhis longtime encouragement and advice on technical writing.Amy Badger must becommended for her wonderful waterfall illustration, and we also thank Hans Bodlaenderfor letting us use the nifty chess font he developed as a hobby project.

Page 102: The Android Developer's Collection

About the AuthorsLauren Darcey is responsible for the technical leadership and direction of a small soft-ware company specializing in mobile technologies, including Android, iPhone,Blackberry, Palm Pre, BREW, and J2ME and consulting services.With more than twodecades of experience in professional software production, Lauren is a recognizedauthority in application architecture and the development of commercial-grade mobileapplications. Lauren received a B.S. in Computer Science from the University ofCalifornia, Santa Cruz.

She spends her copious free time traveling the world with her geeky mobile-mindedhusband and is an avid nature photographer. Her work has been published in books andnewspapers around the world. In South Africa, she dove with 4-meter-long great whitesharks and got stuck between a herd of rampaging hippopotami and an irritated bull ele-phant. She’s been attacked by monkeys in Japan, gotten stuck in a ravine with two hun-gry lions in Kenya, gotten thirsty in Egypt, narrowly avoided a coup d’état in Thailand,geocached her way through the Swiss Alps, drank her way through the beer halls ofGermany, slept in the crumbling castles of Europe, and gotten her tongue stuck to aniceberg in Iceland (while being watched by a herd of suspicious wild reindeer).

Shane Conder has extensive development experience and has focused his attention onmobile and embedded development for the past decade. He has designed and developedmany commercial applications for Android, iPhone, BREW, Blackberry, J2ME, Palm, andWindows Mobile—some of which have been installed on millions of phones worldwide.Shane has written extensively about the mobile industry and evaluated mobile develop-ment platforms on his tech blogs and is well known within the blogosphere. Shanereceived a B.S. in Computer Science from the University of California.

A self-admitted gadget freak, Shane always has the latest phone, laptop, or othermobile device. He can often be found fiddling with the latest technologies, such as cloudservices and mobile platforms, and other exciting, state-of-the-art technologies that acti-vate the creative part of his brain. He also enjoys traveling the world with his geeky wife,even if she did make him dive with 4-meter-long great white sharks and almost geteaten by a lion in Kenya. He admits that he has to take at least two phones with himwhen backpacking—even though there is no coverage—that he snickered and whippedout his Android phone to take a picture when Laurie got her tongue stuck to that ice-berg in Iceland, and that he is catching on that he should be writing his own bio.

Page 103: The Android Developer's Collection

This page intentionally left blank

Page 104: The Android Developer's Collection

Introduction

Pioneered by the Open Handset Alliance and Google,Android is a hot, young, free,open source mobile platform making waves in the wireless world.This book providescomprehensive guidance for software development teams on designing, developing, test-ing, debugging, and distributing professional Android applications. If you’re a veteranmobile developer, you can find tips and tricks to streamline the development process andtake advantage of Android’s unique features. If you’re new to mobile development, thisbook provides everything you need to make a smooth transition from traditional softwaredevelopment to mobile development—specifically, its most promising new platform:Android.

Who Should Read This BookThis book includes tips for successful mobile development based on our years in themobile industry and covers everything you need to run a successful Android project fromconcept to completion.We cover how the mobile software process differs from traditionalsoftware development, including tricks to save valuable time and pitfalls to avoid. Regard-less of the size of your project, this book can work for you.

This book was written for several audiences:

n Software developers who want to learn to develop professional Android ap-plications. The bulk of this book is primarily targeted at software developers withJava experience but not necessarily mobile development experience. More seasoneddevelopers of mobile applications can learn how to take advantage of Android andhow it differs from the other technologies of the mobile development market today.

n Quality assurance personnel tasked with testing Android applications.Whetherthey are black box or white box testing, quality assurance engineers can find thisbook invaluable.We devote several chapters to mobile QA concerns, including top-ics such as developing solid test plans and defect tracking systems for mobile appli-cations, how to manage handsets, and how to test applications thoroughly using allthe Android tools available.

n Project managers planning and managing Android development teams. Man-agers can use this book to help plan, hire, and execute Android projects from startto finish.We cover project risk management and how to keep Android projects run-ning smoothly.

Page 105: The Android Developer's Collection

2B Introduction

n Other audiences.This book is useful not only to a software developer, but also forthe corporation looking at potential vertical market applications, the entrepreneurthinking about a cool phone application, and hobbyists looking for some fun withtheir new phone. Businesses seeking to evaluate Android for their specific needs(including feasibility analysis) can also find the information provided valuable.Any-one with an Android handset and a good idea for a mobile application can put thisbook to use for fun and profit.

Key Questions Answered in This BookThis book answers the following questions:

1. What is Android? How do the SDK versions differ?

2. How is Android different from other mobile technologies, and how can developerstake advantage of these differences?

3. How do developers use the Eclipse Development Environment for Java to developand debug Android applications on the emulator and handsets?

4. How are Android applications structured?

5. How do developers design robust user interfaces for mobile—specifically, for Android?

6. What capabilities does the Android SDK have and how can developers use them?

7. How does the mobile development process differ from traditional desktopdevelopment?

8. What development strategies work best for Android development?

9. What do managers, developers, and testers need to look for when planning, devel-oping, and testing a mobile development application?

10. How do mobile teams design bulletproof Android applications for publication?

11. How do mobile teams package Android applications for deployment?

12. How do mobile teams make money from Android applications?

13. And, finally, what is new in the second edition of the book?

How This Book Is StructuredThis book is divided into seven parts.The first five parts are primarily of interest to devel-opers; Parts VI and VII provide lots of helpful information for project managers and qual-ity assurance personnel as well as developers.

Page 106: The Android Developer's Collection

3BAn Overview of Changes in This Edition

Here is an overview of the various parts in this book:

n Part I:An Overview of Android

Part I provides an introduction to Android, explaining how it differs from othermobile platforms.You become familiar with the Android SDK and tools, install thedevelopment tools, and write and run your first Android application—on the emu-lator and on a handset.

n Part II:Android Application Design Essentials

Part II introduces the design principles necessary to write Android applications.Youlearn how Android applications are structured and how to include resources, such asstrings, graphics, and user interface components in your projects.

n Part III:Android User Interface Design Essentials

Part III dives deeper into how user interfaces are designed in Android.You learnabout the core user interface element in Android: the View.You also learn about thebasic drawing and animation abilities provided in the Android SDK.

n Part IV: Using Common Android APIs

Part IV is a series of chapters, each devoted to a deeper understanding of the mostimportant APIs within the Android SDK, such as the data and storage APIs (includ-ing file and database usage as well as content providers), networking, telephony,Location-Based Services (LBS), multimedia and 3D graphics APIs, and the optionalhardware APIs available.

n Part V: More Android Application Design Principles

Part V covers more advanced Android application design principles, such as notifica-tions and services.

n Part VI: Deploying Your Android Application to the World

Part VI covers the software development process for mobile, from start to finish,with tips and tricks for project management, software developers, and quality assur-ance personnel.

n Part VII:Appendixes

Part VII includes several helpful quick-start guides for the Android developmenttools: the emulator,ADB and DDMS, Eclipse tips and tricks, and a SQLite tutorial.

An Overview of Changes in This EditionWhen we began writing the first edition of this book, there were no Android devices onthe market. One Android device became available shortly after we started, and it wasavailable only in the United States.Today there are dozens of devices shipping all over theworld.The Android platform has gone through extensive changes since the first edition ofthis book was published.The Android SDK has many new features, and the development

Page 107: The Android Developer's Collection

4B Introduction

tools have received many much-needed upgrades.Android, as a technology, is now onsolid footing within the mobile marketplace.

Within this new edition, we took the opportunity to do a serious overhaul on bookcontent—but don’t worry, it’s still the book readers loved the first time, just bigger, better,and more comprehensive. In addition to adding newly available content, we’ve retestedand upgraded all existing content (text and sample code) for use with the newest AndroidSDKs. Here are some of the highlights of the additions and enhancements we’ve made tothis edition:

n Coverage of the latest and greatest Android tools and utilitiesn Updates to all existing chapters, often with some entirely new sectionsn Complete overhaul of sample code and applications—many more of them, too—

organized by topicn Nine new chapters, which cover new SDK features, including web APIs, the

Android NDK, extending application reach, managing users, data synchronization,backups, advanced user input, and compatibility

n Topics such as Android Manifest files, content providers, designing apps, and testingeach now have their own chapter

n Updated 3D graphics programming, including OpenGL ES 2.0n Coverage of hot topics such as Bluetooth, gestures, voice recognition,App Widgets,

Live Folders, Live Wallpapers, and global searchn Even more tips and tricks from the trenches to help you design, develop, and test

applications for different device targets, including an all-new chapter on tacklingcompatibility issues

n A new appendix full of Eclipse tips and tricks

As you can see, we cover many of the hottest and most exciting features that Android hasto offer.We didn’t take this review lightly; we touched every existing chapter, updatedcontent, and added many new chapters as well. Finally, we included many additions, clari-fications, and, yes, even a few fixes based upon the feedback from our fantastic (andmeticulous) readers.Thank you!

Development Environment Used in This BookThe Android code in this book was written using the following development environments:

n Windows 7 and Mac OS X 10.6.4n Eclipse Java IDE Version 3.5 (Galileo)n Eclipse JDT plug-in and Web Tools Platform (WTP)n Java SE Development Kit (JDK) 6 Update 20

Page 108: The Android Developer's Collection

5BWhere to Find More Information

n Android SDK Version 2.2,API Level 8 (FroYo)

1. ADT Plug-in for Eclipse 0.9.9

2. NDK Tools Revision 4b

3. SDK Tools Revision 7n Android Handsets:T-Mobile G1, HTC Nexus One, HTC Evo 4G, Motorola

Droid,ARCHOS 5 internet tablet

Supplementary Materials AvailableThe source code that accompanies this book for download on the publisher website:http://www.informit.com/title/9780321743015.

We also run a blog at http://androidbook.blogspot.com, which covers a variety ofAndroid topics and presents reader feedback, questions, and further information.You canalso find links to our various technical articles.

Where to Find More InformationThere is a vibrant, helpful Android developer community on the Web. Here are a numberof useful websites for Android developers and followers of the wireless industry:

n Android Developer Website: The Android SDK and developer reference site:

http://developer.android.com/

n Stack Overflow: The Android website with great technical information (completewith tags) and an official support forum for developers:

http://stackoverflow.com/questions/tagged/android

n Open Handset Alliance: Android manufacturers, operators, and developers:

http://www.openhandsetalliance.com/

n Android Market: Buy and sell Android applications:

http://www.android.com/market/

n Mobiletuts+: Mobile development tutorials, including Android:

http://mobile.tutsplus.com/category/tutorials/android/

n anddev.org: An Android developer forum:

http://www.anddev.org

n Google Team Android Apps: Open source Android applications:

http://apps-for-android.googlecode.com/

Page 109: The Android Developer's Collection

6B Introduction

n FierceDeveloper:A weekly newsletter for wireless developers:

http://www.fiercedeveloper.com/

n Wireless Developer Network:Daily news on the wireless industry:

http://www.wirelessdevnet.com/

n Developer.com:A developer-oriented site with mobile articles:

http://www.developer.com/

Conventions Used in This BookThis book uses the following conventions:

n ➥ is used to signify to readers that the authors meant for the continued code to ap-pear on the same line. No indenting should be done on the continued line.

n Code or programming terms are set in monospace text.

This book also presents information in the following sidebars:

TipTips provide useful information or hints related to the current text.

NoteNotes provide additional information that might be interesting or relevant.

WarningWarnings provide hints or tips about pitfalls that you might encounter and how to avoid them.

Contacting the AuthorsWe welcome your comments, questions, and feedback.We invite you to visit our blog athttp://androidbook.blogspot.comor email us at [email protected]

Page 110: The Android Developer's Collection

1Introducing Android

The mobile development community is at a tipping point. Mobile users demand morechoice, more opportunities to customize their phones, and more functionality. Mobileoperators want to provide value-added content to their subscribers in a manageable andlucrative way. Mobile developers want the freedom to develop the powerful mobile appli-cations users demand with minimal roadblocks to success. Finally, handset manufacturerswant a stable, secure, and affordable platform to power their devices. Up until now a sin-gle mobile platform has adequately addressed the needs of all the parties.

Enter Android, which is a potential game-changer for the mobile development com-munity.An innovative and open platform,Android is well positioned to address the grow-ing needs of the mobile marketplace.

This chapter explains what Android is, how and why it was developed, and where theplatform fits in to the established mobile marketplace.

A Brief History of Mobile Software DevelopmentTo understand what makes Android so compelling, we must examine how mobile devel-opment has evolved and how Android differs from competing platforms.

Way Back WhenRemember way back when a phone was just a phone? When we relied on fixed land-lines? When we ran for the phone instead of pulling it out of our pocket? When we lostour friends at a crowded ballgame and waited around for hours hoping to reunite? Whenwe forgot the grocery list (see Figure 1.1) and had to find a payphone or drive backhome again?

Those days are long gone.Today, commonplace problems such as these are easilysolved with a one-button speed dial or a simple text message like “WRU?” or “20?” or“Milk and?”

Our mobile phones keep us safe and connected. Now we roam around freely, relyingon our phones not only to keep in touch with friends, family, and coworkers, but also to

Page 111: The Android Developer's Collection

8B Chapter 1 Introducing Android

Consider the following true story, which has been slightly enhanced for effect:

Once upon a time, on a warm summer evening, I was happily minding my own businesscooking dinner in my new house in rural New Hampshire when a bat swooped over myhead, scaring me to death.

The first thing I did—while ducking—was to pull out my cell phone and send a text mes-sage to my husband, who was across the country at the time. I typed, “There’s a bat inthe house!”

My husband did not immediately respond (a divorce-worthy incident, I thought at thetime), so I called my dad and asked him for suggestions on how to get rid of the bat.

He just laughed.

Figure 1.1 Mobile phones have become a crucial shopping accessory.

tell us where to go, what to do, and how to do it. Even the most domestic of events seemto revolve around my mobile phone.

Page 112: The Android Developer's Collection

9BA Brief History of Mobile Software Development

Annoyed, I snapped a picture of the bat with my phone and sent it to my husband and myblog, simultaneously guilt-tripping him and informing the world of my treacherous domes-tic wildlife encounter.

Finally, I googled “get rid of a bat” and then I followed the helpful do-it-yourself instruc-tions provided on the Web for people in my situation. I also learned that late August iswhen baby bats often leave the roost for the first time and learn to fly. Newly aware that Ihad a baby bat on my hands, I calmly got a broom and managed to herd the bat out ofthe house.

Problem solved—and I did it all with the help of my trusty cell phone, the old LG VX9800.

My point here? Mobile phones can solve just about anything—and we rely on them foreverything these days.

You notice that I used half a dozen different mobile applications over the course ofthis story. Each application was developed by a different company and had a different userinterface. Some were well designed; others not so much. I paid for some of the applica-tions, and others came on my phone.

As a user, I found the experience functional, but not terribly inspiring.As a mobile de-veloper, I wished for an opportunity to create a more seamless and powerful applicationthat could handle all I’d done and more. I wanted to build a better bat trap, if you will.

Before Android, mobile developers faced many roadblocks when it came to writingapplications. Building the better application, the unique application, the competing appli-cation, the hybrid application, and incorporating many common tasks such as messagingand calling in a familiar way were often unrealistic goals.

To understand why, let’s take a brief look at the history of mobile software development.

“The Brick”The Motorola DynaTAC 8000X was the first commercially available cell phone. Firstmarketed in 1983, it was 13 × 1.75 × 3.5 inches in dimension, weighed about 2.5 pounds,and allowed you to talk for a little more than half an hour. It retailed for $3,995, plushefty monthly service fees and per-minute charges.

We called it “The Brick,” and the nickname stuck for many of those early mobilephones we alternatively loved and hated.About the size of a brick, with a battery powerjust long enough for half a conversation, these early mobile handsets were mostly seen inthe hands of traveling business execs, security personnel, and the wealthy. First-generationmobile phones were just too expensive.The service charges alone would bankrupt the av-erage person, especially when roaming.

Early mobile phones were not particularly full featured. (Although, even the MotorolaDynaTAC, shown in Figure 1.2, had many of the buttons we’ve come to know well, suchas the SEND, END, and CLR buttons.) These early phones did little more than make andreceive calls and, if you were lucky, there was a simple contacts application that wasn’t im-possible to use.

Page 113: The Android Developer's Collection

10B Chapter 1 Introducing Android

1 2 3

4 5 6

7 8 9

* 0 #

Figure 1.2 The first commercially available mobile phone: the Motorola DynaTAC.

The first-generation mobile phones were designed and developed by the handsetmanufacturers. Competition was fierce and trade secrets were closely guarded. Manufac-turers didn’t want to expose the internal workings of their handsets, so they usually devel-oped the phone software in-house.As a developer, if you weren’t part of this inner circle,you had no opportunity to write applications for the phones.

It was during this period that we saw the first “time-waster” games begin to appear.Nokia was famous for putting the 1970s video game Snake on some of its earliest mono-chrome phones. Other manufacturers followed suit, adding games such as Pong,Tetris,and Tic-Tac-Toe.

These early phones were flawed, but they did something important—they changed theway people thought about communication.As mobile phone prices dropped, batteriesimproved, and reception areas grew, more and more people began carrying these handydevices. Soon mobile phones were more than just a novelty.

Customers began pushing for more features and more games. But there was a problem.The handset manufacturers didn’t have the motivation or the resources to build every ap-plication users wanted.They needed some way to provide a portal for entertainment andinformation services without allowing direct access to the handset.

What better way to provide these services than the Internet?

Page 114: The Android Developer's Collection

11BA Brief History of Mobile Software Development

Wireless Application Protocol (WAP)As it turned out, allowing direct phone access to the Internet didn’t scale well for mobile.

By this time, professional websites were full color and chock full of text, images, andother sorts of media.These sites relied on JavaScript, Flash, and other technologies to en-hance the user experience, and they were often designed with a target resolution of800x600 pixels and higher.

When the first clamshell phone, the Motorola StarTAC, was released in 1996, it merelyhad an LCD 10-digit segmented display. (Later models would add a dot-matrix type dis-play.) Meanwhile, Nokia released one of the first slider phones, the 8110—fondly referredto as “The Matrix Phone” because the phone was heavily used in films.The 8110 coulddisplay four lines of text with 13 characters per line. Figure 1.3 shows some of the com-mon phone form factors.

With their postage stamp-sized low-resolution screens and limited storage and process-ing power, these phones couldn’t handle the data-intensive operations required by tradi-tional web browsers.The bandwidth requirements for data transmission were also costlyto the user.

The Wireless Application Protocol (WAP) standard emerged to address these concerns.Simply put,WAP was a stripped-down version of HTTP, which is the backbone protocolof the Internet. Unlike traditional web browsers,WAP browsers were designed to runwithin the memory and bandwidth constraints of the phone.Third-party WAP sites

Figure 1.3 Various mobile phone form factors: the candy bar, theslider, and the clamshell.

Page 115: The Android Developer's Collection

served up pages written in a markup language called Wireless Markup Language (WML).These pages were then displayed on the phone’s WAP browser. Users navigated as theywould on the Web, but the pages were much simpler in design.

The WAP solution was great for handset manufacturers.The pressure was off—theycould write one WAP browser to ship with the handset and rely on developers to comeup with the content users wanted.

The WAP solution was great for mobile operators.They could provide a custom WAPportal, directing their subscribers to the content they wanted to provide, and rake in thedata charges associated with browsing, which were often high.

Developers and content providers didn’t deliver. For the first time, developers had achance to develop content for phone users, and some did so, with limited success.

Most of the early WAP sites were extensions of popular branded websites, such asCNN.com and ESPN.com, which were looking for new ways to extend their reader-ship. Suddenly phone users accessed the news, stock market quotes, and sports scores ontheir phones.

Commercializing WAP applications was difficult, and there was no built-in billingmechanism. Some of the most popular commercial WAP applications that emerged dur-ing this time were simple wallpaper and ringtone catalogues that enabled users to person-alize their phones for the first time. For example, a user browsed a WAP site and requesteda specific item. He filled out a simple order form with his phone number and his handsetmodel. It was up to the content provider to deliver an image or audio file compatiblewith the given phone. Payment and verification were handled through various premium-priced delivery mechanisms such as Short Message Service (SMS), Enhanced MessagingService (EMS), Multimedia Messaging Service (MMS), and WAP Push.

WAP browsers, especially in the early days, were slow and frustrating.Typing longURLs with the numeric keypad was onerous.WAP pages were often difficult to navi-gate. Most WAP sites were written one time for all phones and did not account for indi-vidual phone specifications. It didn’t matter if the end user’s phone had a big color screenor a postage stamp-sized monochrome screen; the developer couldn’t tailor the user’s ex-perience.The result was a mediocre and not very compelling experience for everyoneinvolved.

Content providers often didn’t bother with a WAP site and instead just advertised SMSshort codes on TV and in magazines. In this case, the user sent a premium SMS messagewith a request for a specific wallpaper or ringtone, and the content provider sent it back.Mobile operators generally liked these delivery mechanisms because they received a largeportion of each messaging fee.

WAP fell short of commercial expectations. In some markets, such as Japan, it flour-ished, whereas in others, such as the United States, it failed to take off. Handset screenswere too small for surfing. Reading a sentence fragment at a time, and then waiting sec-onds for the next segment to download, ruined the user experience, especially becauseevery second of downloading was often charged to the user. Critics began to call WAP“Wait and Pay.”

12B Chapter 1 Introducing Android

Page 116: The Android Developer's Collection

13BA Brief History of Mobile Software Development

Finally, the mobile operators who provided the WAP portal (the default home pageloaded when you started your WAP browser) often restricted which WAP sites were ac-cessible.The portal enabled the operator to restrict the number of sites users could browseand to funnel subscribers to the operator’s preferred content providers and exclude com-peting sites.This kind of walled garden approach further discouraged third-party develop-ers, who already faced difficulties in monetizing applications, from writing applications.

Proprietary Mobile PlatformsIt came as no surprise that users wanted more—they will always want more.

Writing robust applications with WAP, such as graphic-intensive video games, wasnearly impossible.The 18-year-old to 25-year-old sweet-spot demographic—the kidswith the disposable income most likely to personalize their phones with wallpapers andringtones—looked at their portable gaming systems and asked for a device that was botha phone and a gaming device or a phone and a music player.They argued that if devicessuch as Nintendo’s Game Boy could provide hours of entertainment with only five but-tons, why not just add phone capabilities? Others looked to their digital cameras, Palms,BlackBerries, iPods, and even their laptops and asked the same question.The marketseemed to be teetering on the edge of device convergence.

Memory was getting cheaper, batteries were getting better, and PDAs and other em-bedded devices were beginning to run compact versions of common operating systemssuch as Linux and Windows.The traditional desktop application developer was suddenly aplayer in the embedded device market, especially with smartphone technologies such asWindows Mobile, which they found familiar.

Handset manufacturers realized that if they wanted to continue to sell traditionalhandsets, they needed to change their protectionist policies pertaining to handset designand expose their internal frameworks to some extent.

A variety of different proprietary platforms emerged—and developers are still activelycreating applications for them. Some smartphone devices ran Palm OS (now Garnet OS)and RIM BlackBerry OS. Sun Microsystems took its popular Java platform and J2MEemerged (now known as Java Micro Edition [Java ME]). Chipset maker Qualcomm de-veloped and licensed its Binary Runtime Environment for Wireless (BREW). Other plat-forms, such as Symbian OS, were developed by handset manufacturers such as Nokia,Sony Ericsson, Motorola, and Samsung.The Apple iPhone OS (OS X iPhone) joined theranks in 2008. Figure 1.4 shows several different phones, all of which have different devel-opment platforms.

Many of these platforms have associated developer programs.These programs keep thedeveloper communities small, vetted, and under contractual agreements on what they canand cannot do.These programs are often required and developers must pay for them.

Each platform has benefits and drawbacks. Of course, developers love to debate aboutwhich platform is “the best.” (Hint: It’s usually the platform we’re currently developing for.)

The truth is that no one platform has emerged victorious. Some platforms are bestsuited for commercializing games and making millions—if your company has brand

Page 117: The Android Developer's Collection

Figure 1.4 Phones from various mobile device platforms.

For manufacturers and mobile operators, handset product lines quickly became com-plicated. Platform market penetration varies greatly by region and user demographic. In-stead of choosing just one platform, manufacturers and operators have been forced tosell phones for all the different platforms to compete in the market.We’ve even seensome handsets supporting multiple platforms. (For instance, Symbian phones often alsosupport J2ME.)

The mobile developer community has become as fragmented as the market. It’s nearlyimpossible to keep track of all the changes in the market. Developer specialty niches haveformed.The platform development requirements vary greatly. Mobile software developerswork with distinctly different programming environments, different tools, and differentprogramming languages. Porting among the platforms is often costly and not straightfor-ward. Keeping track of handset configurations and testing requirements, signing and certi-fication programs, carrier relationships, and application marketplaces have becomecomplex spin-off businesses of their own.

14B Chapter 1 Introducing Android

backing. Other platforms are more open and suitable for the hobbyist or vertical marketapplications. No mobile platform is best suited for all possible applications.As a result,the mobile phone has become increasingly fragmented, with all platforms sharing part ofthe pie.

Page 118: The Android Developer's Collection

15BThe Open Handset Alliance

It’s a nightmare for the ACME Company that wants a mobile application. Should itdevelop a J2ME application? BREW? iPhone? Windows Mobile? Everyone has a differ-ent kind of phone.ACME is forced to choose one or, worse, all of the platforms. Someplatforms allow for free applications, whereas others do not.Vertical market applicationopportunities are limited and expensive.

As a result, many wonderful applications have not reached their desired users, andmany other great ideas have not been developed at all.

The Open Handset AllianceEnter search advertising giant Google. Now a household name, Google has shown an in-terest in spreading its vision, its brand, its search and ad-revenue-based platform, and itssuite of tools to the wireless marketplace.The company’s business model has been amaz-ingly successful on the Internet and, technically speaking, wireless isn’t that different.

Google Goes WirelessThe company’s initial forays into mobile were beset with all the problems you would ex-pect.The freedoms Internet users enjoyed were not shared by mobile phone subscribers.Internet users can choose from the wide variety of computer brands, operating systems,Internet service providers, and web browser applications.

Nearly all Google services are free and ad driven. Many applications in the GoogleLabs suite directly compete with the applications available on mobile phones.The appli-cations range from simple calendars and calculators to navigation with Google Maps andthe latest tailored news from News Alerts—not to mention corporate acquisitions such asBlogger and YouTube.

When this approach didn’t yield the intended results, Google decided to a different ap-proach—to revamp the entire system upon which wireless application development wasbased, hoping to provide a more open environment for users and developers: the Internetmodel.The Internet model allows users to choose between freeware, shareware, and paidsoftware.This enables free market competition among services.

Forming the Open Handset AllianceWith its user-centric, democratic design philosophies, Google has led a movement to turnthe existing closely guarded wireless market into one where phone users can move be-tween carriers easily and have unfettered access to applications and services.With its vastresources, Google has taken a broad approach, examining the wireless infrastructure fromthe FCC wireless spectrum policies to the handset manufacturers’ requirements, applica-tion developer needs, and mobile operator desires.

Next, Google joined with other like-minded members in the wireless community andposed the following question:What would it take to build a better mobile phone?

The Open Handset Alliance (OHA) was formed in November 2007 to answer thatvery question.The OHA is a business alliance comprised of many of the largest and most

Page 119: The Android Developer's Collection

successful mobile companies on the planet. Its members include chip makers, handsetmanufacturers, software developers, and service providers.The entire mobile supply chainis well represented.

Andy Rubin has been credited as the father of the Android platform. His company,Android Inc., was acquired by Google in 2005.Working together, OHA members, includ-ing Google, began developing a nonproprietary open standard platform based upon tech-nology developed at Android Inc. that would aim to alleviate the aforementionedproblems hindering the mobile community.The result is the Android project.To this day,most Android platform development is completed by Rubin’s team at Google, where heacts as VP of Engineering and manages the Android platform roadmap.

Google’s involvement in the Android project has been so extensive that the line be-tween who takes responsibility for the Android platform (the OHA or Google) hasblurred. Google hosts the Android open source project and provides online Android doc-umentation, tools, forums, and the Software Development Kit (SDK) for developers.Allmajor Android news originates at Google.The company has also hosted a number ofevents at conferences and the Android Developer Challenge (ADC), a contest to encour-age developers to write killer Android applications—for $10 million dollars in prizes tospur development on the platform.The winners and their apps are listed on the Androidwebsite.

Manufacturers: Designing the Android HandsetsMore than half the members of the OHA are handset manufacturers, such as Samsung,Motorola, HTC, and LG, and semiconductor companies, such as Intel,Texas Instruments,NVIDIA, and Qualcomm.These companies are helping design the first generation of An-droid handsets.

The first shipping Android handset—the T-Mobile G1—was developed by handsetmanufacturer HTC with service provided by T-Mobile. It was released in October 2008.Many other Android handsets were slated for 2009 and early 2010.The platform gainedmomentum relatively quickly. Each new Android device was more powerful and excitingthan the last. Over the following 18 months, 60 different Android handsets (made by 21different manufacturers) debuted across 59 carriers in 48 countries around the world. ByJune 2010, at an announcement of a new, highly anticipated Android handset, Google an-nounced more than 160,000 Android devices were being activated each day (for a rate ofnearly 60 million devices annually).The advantages of widespread manufacturer and car-rier support appear to be really paying off at this point.

The Android platform is now considered a success. It has shaken the mobile market-place, gaining ground steadily against competitive platforms such as the Apple iPhone,RIM BlackBerry, and Windows Mobile.The latest numbers (as of Summer 2010) showBlackBerry in the lead with a declining 31% of the smartphone market.Trailing close be-hind is Apple’s iPhone at 28%.Android, however, is trailing with 19%, though it’s gainingground rapidly and, according to some sources, is the fastest-selling smartphone platform.Microsoft Windows Mobile has been declining and now trails Android by several percent-age points.

16B Chapter 1 Introducing Android

Page 120: The Android Developer's Collection

17BThe Open Handset Alliance

Mobile Operators: Delivering the Android ExperienceAfter you have the phones, you have to get them out to the users. Mobile operators fromNorth, South, and Central America; Europe,Asia, India,Australia,Africa, and the MiddleEast have joined the OHA, ensuring a worldwide market for the Android movement.With almost half a billion subscribers alone, telephony giant China Mobile is a foundingmember of the alliance.

Much of Android’s success is also due to the fact that many Android handsets don’tcome with the traditional “smartphone price tag”—quite a few are offered free with acti-vation by carriers. Competitors such as the Apple iPhone have no such offering as of yet.For the first time, the average Jane or Joe can afford a feature-full phone. I’ve lost count ofthe number of times I’ve had a waitress, hotel night manager, or grocery store checkoutperson tell me that they just got an Android phone and it has changed their life.This phe-nomenon has only added to the Android’s rising underdog status.

In the United States, the Android platform was given a healthy dose of help from car-riers such as Verizon, who launched a $100 million dollar campaign for the first Droidhandset. Many other Droid-style phones have followed from other carriers. Sprint re-cently launched the Evo 4G (America’s first 4G phone) to much fanfare and record one-day sales (http://j.mp/cNhb4b).

Content Providers: Developing Android ApplicationsWhen users have Android handsets, they need those killer apps, right?

Google has led the pack, developing Android applications, many of which, such as theemail client and web browser, are core features of the platform. OHA members are alsoworking on Android application integration. eBay, for example, is working on integrationwith its online auctions.

The first ADC received 1,788 submissions, with the second ADC being voted upon by26,000 Android users to pick a final 200 applications that would be judged profession-ally—all newly developed Android games, productivity helpers, and a slew of location-based services (LBS) applications.We also saw humanitarian, social networking, andmash-up apps. Many of these applications have debuted with users through the AndroidMarket—Google’s software distribution mechanism for Android. For now, these chal-lenges are over.The results, though, are still impressive.

For those working on the Android platform from the beginning, handsets couldn’tcome fast enough.The T-Mobile G1 was the first commercial Android device on themarket, but it had the air of a developer pre-release handset. Subsequent Android handsetshave had much more impressive hardware, allowing developers to dive in and design awe-some new applications.

Page 121: The Android Developer's Collection

As of October 2010, there are more than 80,000 applications available in the AndroidMarket, which is growing rapidly.This takes into account only applications publishedthrough this one marketplace—not the many other applications sold individually or onother markets.This also does not take into account that, as of Android 2.2, Flash applica-tions can run on Android handsets.This opens up even more application choices for An-droid users and more opportunities for Android developers.

There are now more than 180,000 Android developers writing interesting and excitingapplications. By the time you finish reading this book, you will be adding your expertiseto this number.

Taking Advantage of All Android Has to OfferAndroid’s open platform has been embraced by much of the mobile development com-munity—extending far beyond the members of the OHA.

As Android phones and applications have become more readily available, many othermobile operators and handset manufacturers have jumped at the chance to sell Androidphones to their subscribers, especially given the cost benefits compared to proprietaryplatforms.The open standard of the Android platform has resulted in reduced operatorcosts in licensing and royalties, and we are now seeing a migration to open handsets fromproprietary platforms such as RIM,Windows Mobile, and the Apple iPhone.The markethas cracked wide open; new types of users are able to consider smartphones for the firsttime.Android is well suited to fill this demand.

Android Platform DifferencesAndroid is hailed as “the first complete, open, and free mobile platform”:

n Complete:The designers took a comprehensive approach when they developed theAndroid platform.They began with a secure operating system and built a robust soft-ware framework on top that allows for rich application development opportunities.

n Open:The Android platform is provided through open source licensing. Develop-ers have unprecedented access to the handset features when developing applica-tions.

n Free: Android applications are free to develop.There are no licensing or royalty feesto develop on the platform. No required membership fees. No required testing fees.No required signing or certification fees.Android applications can be distributedand commercialized in a variety of ways.

Android: A Next-Generation PlatformAlthough Android has many innovative features not available in existing mobile plat-forms, its designers also leveraged many tried-and-true approaches proven to work in thewireless world. It’s true that many of these features appear in existing proprietary

18B Chapter 1 Introducing Android

Page 122: The Android Developer's Collection

19BAndroid Platform Differences

Figure 1.5 The Android mascot and logo.

platforms, but Android combines them in a free and open fashion while simultaneouslyaddressing many of the flaws on these competing platforms.

The Android mascot is a little green robot, shown in Figure 1.5.This little guy (girl?) isoften used to depict Android-related materials.

Android is the first in a new generation of mobile platforms, giving its platform devel-opers a distinct edge on the competition.Android’s designers examined the benefits anddrawbacks of existing platforms and then incorporated their most successful features.Atthe same time,Android’s designers avoided the mistakes others suffered in the past.

Since the Android 1.0 SDK was released,Android platform development has continuedat a fast and furious pace. For quite some time, there was a new Android SDK out everycouple of months! In typical tech-sector jargon, each Android SDK has had a projectname. In Android’s case, the SDKs are named alphabetically after sweets (see Figure 1.6).

The latest version of Android is codenamed Gingerbread.

Figure 1.6 Some Android SDKs and their codenames.

Page 123: The Android Developer's Collection

Free and Open SourceAndroid is an open source platform. Neither developers nor handset manufacturers payroyalties or license fees to develop for the platform.

The underlying operating system of Android is licensed under GNU General PublicLicense Version 2 (GPLv2), a strong “copyleft” license where any third-party improve-ments must continue to fall under the open source licensing agreement terms.The An-droid framework is distributed under the Apache Software License (ASL/Apache2),which allows for the distribution of both open- and closed-source derivations of thesource code. Commercial developers (handset manufacturers especially) can choose to en-hance the platform without having to provide their improvements to the open sourcecommunity. Instead, developers can profit from enhancements such as handset-specificimprovements and redistribute their work under whatever licensing they want.

Android application developers have the ability to distribute their applications underwhatever licensing scheme they prefer. Developers can write open source freeware or tra-ditional licensed applications for profit and everything in between.

Familiar and Inexpensive Development ToolsUnlike some proprietary platforms that require developer registration fees, vetting, andexpensive compilers, there are no upfront costs to developing Android applications.

Freely Available Software Development KitThe Android SDK and tools are freely available. Developers can download the AndroidSDK from the Android website after agreeing to the terms of the Android Software De-velopment Kit License Agreement.

Familiar Language, Familiar Development EnvironmentsDevelopers have several choices when it comes to integrated development environments(IDEs). Many developers choose the popular and freely available Eclipse IDE to designand develop Android applications. Eclipse is the most popular IDE for Android develop-ment, and there is an Android plug-in available for facilitating Android development.An-droid applications can be developed on the following operating systems:

n Windows XP (32-bit) or Vista (32-bit or 64-bit)n Mac OS X 10.5.8 or later (x86 only)n Linux (tested on Linux Ubuntu 8.04 LTS, Hardy Heron)

Reasonable Learning Curve for DevelopersAndroid applications are written in a well-respected programming language: Java.

The Android application framework includes traditional programming constructs, suchas threads and processes and specially designed data structures to encapsulate objects com-monly used in mobile applications. Developers can rely on familiar class libraries, such asjava.net and java.text. Specialty libraries for tasks such as graphics and database

20B Chapter 1 Introducing Android

Page 124: The Android Developer's Collection

21BAndroid Platform Differences

management are implemented using well-defined open standards such as OpenGL Em-bedded Systems (OpenGL ES) or SQLite.

Enabling Development of Powerful ApplicationsIn the past, handset manufacturers often established special relationships with trustedthird-party software developers (OEM/ODM relationships).This elite group of softwaredevelopers wrote native applications, such as messaging and web browsers, which shippedon the handset as part of the phone’s core feature set.To design these applications, themanufacturer would grant the developer privileged inside access and knowledge of ahandset’s internal software framework and firmware.

On the Android platform, there is no distinction between native and third-party appli-cations, enabling healthy competition among application developers.All Android applica-tions use the same libraries.Android applications have unprecedented access to theunderlying hardware, allowing developers to write much more powerful applications.Ap-plications can be extended or replaced altogether. For example,Android developers arenow free to design email clients tailored to specific email servers, such as Microsoft Ex-change or Lotus Notes.

Rich, Secure Application IntegrationRecall from the bat story I previously shared that I accessed a variety of phone applica-tions in the course of a few moments: text messaging, phone dialer, camera, email, picturemessaging, and the browser. Each was a separate application running on the phone—some built-in and some purchased. Each had its own unique user interface. None weretruly integrated.

Not so with Android. One of the Android platform’s most compelling and innovativefeatures is well-designed application integration.Android provides all the tools necessaryto build a better “bat trap,” if you will, by allowing developers to write applications thatseamlessly leverage core functionality such as web browsing, mapping, contact manage-ment, and messaging.Applications can also become content providers and share their dataamong each other in a secure fashion.

Platforms such as Symbian have suffered from setbacks due to malware.Android’s vig-orous application security model helps protect the user and the system from malicioussoftware.

No Costly Obstacles to PublicationAndroid applications have none of the costly and time-intensive testing and certificationprograms required by other platforms such as BREW and Symbian.

Page 125: The Android Developer's Collection

A “Free Market” for ApplicationsAndroid developers are free to choose any kind of revenue model they want.They candevelop freeware, shareware, or trial-ware applications, ad-driven, and paid applications.Android was designed to fundamentally change the rules about what kind of wireless ap-plications could be developed. In the past, developers faced many restrictions that had lit-tle to do with the application functionality or features:

n Store limitations on the number of competing applications of a given typen Store limitations on pricing, revenue models, and royaltiesn Operator unwillingness to provide applications for smaller demographics

With Android, developers can write and successfully publish any kind of application theywant. Developers can tailor applications to small demographics, instead of just large-scalemoney-making ones often insisted upon by mobile operators.Vertical market applicationscan be deployed to specific, targeted users.

Because developers have a variety of application distribution mechanisms to choosefrom, they can pick the methods that work for them instead of being forced to play by oth-ers’ rules.Android developers can distribute their applications to users in a variety of ways:

n Google developed the Android Market (see Figure 1.7), a generic Android applica-tion store with a revenue-sharing model.

22B Chapter 1 Introducing Android

Figure 1.7 The Android market.

n Handango.com added Android applications to its existing catalogue using theirbilling models and revenue-sharing model.

n Developers can come up with their own delivery and payment mechanisms.

Mobile operators are still free to develop their own application stores and enforce theirown rules, but it will no longer be the only opportunity developers have to distributetheir applications.

A New and Growing PlatformAndroid might be the next generation in mobile platforms, but the technology is still inits early stages. Early Android developers have had to deal with the typical roadblocks as-sociated with a new platform: frequently revised SDKs, lack of good documentation, andmarket uncertainties.

On the other hand, developers diving into Android development now benefit fromthe first-to-market competitive advantages we’ve seen on other platforms such as BREW

Page 126: The Android Developer's Collection

23BThe Android Platform

and Symbian. Early developers who give feedback are more likely to have an impact onthe long-term design of the Android platform and what features will come in the nextversion of the SDK. Finally, the Android forum community is lively and friendly. Incen-tive programs, such as the ADC, have encouraged many new developers to dig into theplatform.

Each new version of the Android SDK has provided a number of substantial improve-ments to the platform. In recent revisions, the Android platform has received some much-needed UI “polish,” both in terms of visual appeal and performance.Although most ofthese upgrades and improvements were welcome and necessary, new SDK versions oftencause some upheaval within the Android developer community.A number of publishedapplications have required retesting and resubmission to the Android Marketplace to con-form to new SDK requirements, which are quickly rolled out to all Android phones inthe field as a firmware upgrade, rendering older applications obsolete.

Some older Android handsets are not capable of running the latest versions of the plat-form.This means that Android developers often need to target several different SDK ver-sions to reach all users. Luckily, the Android development tools make this easier than ever.

The Android PlatformAndroid is an operating system and a software platform upon which applications are de-veloped.A core set of applications for everyday tasks, such as web browsing and email, areincluded on Android handsets.

As a product of the OHA’s vision for a robust and open source development environ-ment for wireless,Android is an emerging mobile development platform.The platform wasdesigned for the sole purpose of encouraging a free and open market that all mobile appli-cations phone users might want to have and software developers might want to develop.

Android’s Underlying ArchitectureThe Android platform is designed to be more fault-tolerant than many of its predecessors.The handset runs a Linux operating system upon which Android applications are exe-cuted in a secure fashion. Each Android application runs in its own virtual machine (seeFigure 1.8).Android applications are managed code; therefore, they are much less likely tocause the phone to crash, leading to fewer instances of device corruption (also called“bricking” the phone, or rendering it useless).

The Linux Operating SystemThe Linux 2.6 kernel handles core system services and acts as a hardware abstraction layer(HAL) between the physical hardware of the handset and the Android software stack.

Some of the core functions the kernel handles include

n Enforcement of application permissions and securityn Low-level memory management

Page 127: The Android Developer's Collection

24B Chapter 1 Introducing Android

Physical Hardware

Linux 2.6 Operating System(Hardware Abstraction Layer)

The Android Platform

Written UsingAndroid

Java Framework

AndroidApplication

A

DALVIK Virtual Machine

Linux UserA

Written UsingAndroid

Java Framework

AndroidApplication

B

DALVIK Virtual Machine

Linux UserB

Written UsingAndroid

Java Framework

AndroidApplication

C

DALVIK Virtual Machine

Linux UserC

MemoryManagement

ProcessManagement

Binder IPC

I/O

DisplayKeypad

Touchscreen

PowerManagement

Other DriversWiFi, Bluetooth, Camera, Audio,

Telephony, Flash, Device Sensors

NetworkStack

Security

Figure 1.8 Diagram of the Android platform architecture.

n Process management and threadingn The network stackn Display, keypad input, camera,Wi-Fi, Flash memory, audio, and binder (IPC)

driver access

Page 128: The Android Developer's Collection

25BThe Android Platform

Android Application Runtime EnvironmentEach Android application runs in a separate process, with its own instance of the Dalvikvirtual machine (VM). Based on the Java VM, the Dalvik design has been optimized formobile devices.The Dalvik VM has a small memory footprint, and multiple instances ofthe Dalvik VM can run concurrently on the handset.

Security and PermissionsThe integrity of the Android platform is maintained through a variety of security meas-ures.These measures help ensure that the user’s data is secure and that the device is notsubjected to malware.

Applications as Operating System UsersWhen an application is installed, the operating system creates a new user profile associatedwith the application. Each application runs as a different user, with its own private files onthe file system, a user ID, and a secure operating environment.

The application executes in its own process with its own instance of the Dalvik VMand under its own user ID on the operating system.

Explicitly Defined Application PermissionsTo access shared resources on the system,Android applications register for the specificprivileges they require. Some of these privileges enable the application to use phone func-tionality to make calls, access the network, and control the camera and other hardwaresensors.Applications also require permission to access shared data containing private andpersonal information, such as user preferences, user’s location, and contact information.

Applications might also enforce their own permissions by declaring them for other ap-plications to use.The application can declare any number of different permission types,such as read-only or read-write permissions, for finer control over the application.

Limited Ad-Hoc PermissionsApplications that act as content providers might want to provide some on-the-fly permis-sions to other applications for specific information they want to share openly.This is doneusing ad-hoc granting and revoking of access to specific resources using Uniform Re-source Identifiers (URIs).

URIs index specific data assets on the system, such as images and text. Here is an ex-ample of a URI that provides the phone numbers of all contacts:

content://contacts/phones

To understand how this permission process works, let’s look at an example.Let’s say we have an application that keeps track of the user’s public and private birth-

day wish lists. If this application wanted to share its data with other applications, it couldgrant URI permissions for the public wish list, allowing another application permissionto access this list without explicitly having to ask for it.

Page 129: The Android Developer's Collection

26B Chapter 1 Introducing Android

Application Signing for Trust RelationshipsAll Android applications packages are signed with a certificate, so users know that the ap-plication is authentic.The private key for the certificate is held by the developer.Thishelps establish a trust relationship between the developer and the user. It also enables thedeveloper to control which applications can grant access to one another on the system.No certificate authority is necessary; self-signed certificates are acceptable.

Marketplace Developer RegistrationTo publish applications on the popular Android Market, developers must create a devel-oper account.The Android Market is managed closely and no malware is tolerated.

Developing Android ApplicationsThe Android SDK provides an extensive set of application programming interfaces (APIs)that is both modern and robust.Android handset core system services are exposed and ac-cessible to all applications.When granted the appropriate permissions,Android applica-tions can share data among one another and access shared resources on the systemsecurely.

Android Programming Language ChoicesAndroid applications are written in Java (see Figure 1.9). For now, the Java language is thedeveloper’s only choice on the Android platform.

There has been some speculation that other programming languages, such as C++,might be added in future versions of Android. If your application must rely on nativecode in another language such as C or C++, you might want to consider integrating itusing the Android Native Development Kit (NDK).We talk more about this in Chapter18,“Using the Android NDK.”

Figure 1.9 Duke, the Java mascot.

Page 130: The Android Developer's Collection

27BThe Android Platform

No Distinctions Made Between Native and Third-Party ApplicationsUnlike other mobile development platforms, there is no distinction between native appli-cations and developer-created applications on the Android platform. Provided the applica-tion is granted the appropriate permissions, all applications have the same access to corelibraries and the underlying hardware interfaces.

Android handsets ship with a set of native applications such as a web browser and con-tact manager.Third-party applications might integrate with these core applications, ex-tend them to provide a rich user experience, or replace them entirely with alternativeapplications.

Commonly Used PackagesWith Android, mobile developers no longer have to reinvent the wheel. Instead, develop-ers use familiar class libraries exposed through Android’s Java packages to perform com-mon tasks such as graphics, database access, network access, secure communications, andutilities (such as XML parsing).

The Android packages include support for

n Common user interface widgets (Buttons, Spin Controls,Text Input)n User interface layoutn Secure networking and web browsing features (SSL,WebKit)n Structured storage and relational databases (SQLite)n Powerful 2D and 3D graphics (including SGL and OpenGL ES)n Audio and visual media formats (MPEG4, MP3, Still Images)n Access to optional hardware such as location-based services (LBS),Wi-Fi, Blue-

tooth, and hardware sensors

Android Application FrameworkThe Android application framework provides everything necessary to implement your aver-age application.The Android application lifecycle involves the following key components:

n Activities are functions the application performs.n Groups of views define the application’s layout.n Intents inform the system about an application’s plans.n Services allow for background processing without user interaction.n Notifications alert the user when something interesting happens.

Android applications can interact with the operating system and underlying hardware us-ing a collection of managers. Each manager is responsible for keeping the state of someunderlying system service. For example, there is a LocationManager that facilitates inter-action with the location-based services available on the handset.The ViewManager andWindowManager manage user interface fundamentals.

Page 131: The Android Developer's Collection

Applications can interact with one another by using or acting as a ContentProvider.Built-in applications such as the Contact manager are content providers, allowing third-party applications to access contact data and use it in an infinite number of ways.The skyis the limit.

SummaryMobile software development has evolved over time.Android has emerged as a new mo-bile development platform, building on past successes and avoiding past failures of otherplatforms.Android was designed to empower the developer to write innovative applica-tions.The platform is open source, with no up-front fees, and developers enjoy manybenefits over other competing platforms. Now it’s time to dive deeper and start writingAndroid code, so you can evaluate what Android can do for you.

References and More InformationAndroid Development:

http://developer.android.comOpen Handset Alliance:

http://www.openhandsetalliance.com

28B Chapter 1 Introducing Android

Page 132: The Android Developer's Collection

IndexSymbols

# (hash symbol), 111B

… (ellipsis), 136B

3D graphics

cubes, drawing, 378Blighting, 379B-38B2BOpenGL ES, 368BSurfaceView, creating, 370Btexturing, 381B-384Bvertices

coloring, 377B-378Bdrawing, 376B-377B

3GPP Specifications website, 365B

AAbsoluteLayout class, 190B

AbstractAccountAuthenticator class, 490B

abstracted LCD density AVD hardwareoption, 620B

AbstractThreadedSyncAdapter class, 491B

AccelerateDecelerateInterpolator, 230B

AccelerateInterpolator, 230B

accelerometer sensor, 410B-411B, 619B

accessibility framework, 502B-503B

android.speech package, 503Bspeech recognition services,504B-506BText-To-Speech services,

503B, 506B-508Bconverting text into sound files,

508Binitializing, 507Blanguage settings, 507BOnInitListener interface, 506B

Page 133: The Android Developer's Collection

accessing

application preferences, 70BBrowser content provider, 263BContacts private data, 264B-266Bcontent providers with permissions,

262B-263Bdatabase files, 240Bdevice sensors, 408B-409Bhardware, 407Bimages, 270B-271BInternet. See HTTPlayout XML, 126Bmenus, 120Bpreferences, 231B-234Bresources, 103Bsecondary logs, 654Bstrings, 108B-109Btelephony state, 354BWiFi networks, 412B-413B

AccountManager class, 490B, 497B

accounts

AccountManager class, 490Bandroid.accounts package, 489Bauthenticators, 490Bcredentials, protecting, 490Bdeveloper accounts

benefits, 609Bcreating, 604B-606BDistribution Agreement, 604B

providers, 490Bregistering, 490Bsync adapters, 491B

activities

App Widget configuration, 455Bdialogs, adding, 166B-167Bexternal, launching, 77Bgame application examples, 71B

intents, processing, 468Blifecycle, 72B

callbacks, 72B-73Bdestroying activities, 75Binitializing static activity data, 74Bkilling activities, 75Breleasing activity data, 74Bretrieving activity data, 74Bsaving activity data, 74Bsaving state to Bundle objects, 75Bstopping activity data, 74B

live folders, 282B, 481B-482Bmanifest file definition, 92BMapActivity, 324Borganizing with menus, 78Bprimary entry point, 92B-93Breference website, 80Bsearches, creating, 475B-477Bstacks, 72Bstarting, 76B-77Bthemes, applying, 170Btransitioning with intents, 76B

action/data types, 77Bexternal Activities, launching, 77Bnew activities, launching, 76B-77Bpassing additional information, 78B

Activity class, 71B

<activity> tag, 92B

ad revenue, 612B

adapters, 194B

arrays, 194B-195Bbinding data, 196Bcursor, 195B-196Bdatabase data, binding, 254B-256Bevent handling, 197BImageUriAdapter, 272Bsync, 491B, 497B

684B accessing

Page 134: The Android Developer's Collection

AdapterView classes

ArrayAdapter class, 194B-195Bbinding data, 196BCursorAdapter class, 195B-196Bevent handling, 197B

ADB (Android Debug Bridge), 39B

applicationsinstalling, 651Breinstalling, 651Btesting, 656Buninstalling, 651B

backup servicesarchived data, wiping, 655Bcontrolling, 654B-655Bforcing restores, 655Bscheduling, 655B

bug reports, 655B-656Bcommand listing, 660Bconnected devices/emulators, listing,

647B-648Bcopying files, 650Bcustom binaries, installing, 659B-660Bfunctionality, 647BLogCat utility

clearing logs, 654Bdates and times, 652Bfiltering, 652B-653Boutput redirection, 654Bsecondary logs, accessing, 654Bviewing logs, 652B

shell commands, 649B-650Bemulator, starting/stopping,

649B-650Bissuing single, 649Bshell sessions, starting, 649B

specific device commands, 648Bsqlite3B database tool, 656B

starting/stopping server processes,648B

stress testing applicationsevent listening, 656B-657Bevent types, weighting, 657B-658Bmonkey tool, launching, 656Brepeating events, 658Bthrottle, 658B

website, 39BADC (Android Developer Challenge), 16B

addGlobalFocusChangeListener() method,163B

addGlobalLayoutListener() method, 163B

addOnPreDrawListener() method, 163B

addOnTouchModeChangeListener() method,162B

addView() method, 178B

ad-hoc permissions, 25B

Adobe AIR

applications, building, 313Bbeta program, 313BTool Suite website, 314B

ADT plug-in, 35B-36B

AIDL (Android Interface Definition Language)

Parcelable class file, 448Bremote interfaces, declaring, 444B

alert dialogs, 165B

aliases (resources), 123B

alpha transparency transformations, 228B

alternate marketplaces, 610B-611B

alternative layouts, 127B

alternative resources, 102B-103B, 531B

configuration changes, handling, 539Bdata retention, 539Bdefault application icon resources

example, 531B

685Balternative resources

Page 135: The Android Developer's Collection

directory qualifiersAndroid platform, 536B applying, 532Bbad examples, 536B-537Bcase, 532Bcombining, 532Bdefault resources, 536Bdock mode, 534Bgood examples, 536Bkeyboard type and availability, 535Blanguage and region code, 533Bmobile country code, 533Bmobile network code, 533Bnames, 532Bnavigation key availability, 535Bnavigation method, 536Bnight mode, 534Brequired strings, 533Bscreen aspect ratio, 534Bscreen orientation, 534Bscreen pixel density, 534Bscreen size, 533Btext input method, 535Btouch screen type, 535B

efficiency, 538B-539Bhierarchy, 531Binternationalization, 540B-542B

device language and locale example, 541B-542B

dual language support example,540B-541B

performance, 539Bprogrammatic configurations, 538Bscreen orientation customization

example, 537B-538Bwebsites, 549B

AnalogClock class, 156B-157B

Android

benefits, 18Bcompleteness, 18BDebug Bridge. See ADBDev Guide:“Developing on a

Device” website, 67BDeveloper Challenge (ADC), 16BDevelopers blog, 574BDevelopment website, 28B, 398Bfirst-to-market advantages, 23Bfreedoms, 18BInterface Definition Language. See

AIDLmascot/logo, 19Bopen source, 18B, 20Bpackages, 35B, 131B

android.accounts, 489Bandroid.bluetooth, 415Bandroid.content, 232Bandroid.database.sqlite, 239Bandroid.gesture, 509Bandroid.graphics, 230Bandroid.graphics.drawable.shapes,

215Bandroid.hardware, 408B, 412Bandroid.sax.*, 237Bandroid.speech, 503Bandroid.telephony, 354B, 357Bandroid.test, 582Bandroid.util.Xml.*, 237Bandroid.view, 133Bandroid.view.animation, 226Bandroid.webkit, 307Bandroid.widget, 134B

Project Wizard, 44BVirtual Devices. See AVDs

686B alternative resources

Page 136: The Android Developer's Collection

Android Market, 603B-609B

applicationsdeleting, 609Bupgrading, 609Buploading, 606B-608B

country requirements, 604Bdeveloper accounts

benefits, 609Bcreating, 604B-606BDistribution Agreement, 604B

help, 607Blicensing service, 604Bpublication, 608Brefund policy, 608B-609Bsign-up website, 604Bwebsite, 612B

AndroidManifest.xml file, 52B

Android.net package website, 299B

animations, 116B

android.view.animation package, 226Bframe-by-frame, 116B, 117B,

223B-225Banimation loops, naming, 224Bgenie juggling gifts example,

223B-224Bstarting, 224Bstopping, 224B

helper utilities, 116Binterpolators, 230Bloading, 227B-228Bmoving, 229B-230Brotating, 228B-229Bscaling, 229Bstoring, 101Btransparency, 228Btweening, 116B-118B, 224B-230B

defining as XML resources, 226Bdefining programmatically, 226B

loading, 227B-228Bmoving transformations,

229B-230Brotating, 228B-229Bscaling, 229Bsimultaneously/sequentially,

226B-227Btransformations, defining, 224Btransparency, 228B

types, 221B-223BAnimationUtils class, 227B-228B

antialiasing paints, 207B

AnticipateInterpolator, 230B

AnticipateOvershootInterpolator, 230B

Apache Software License (ASL/Apache2),20B

API levels

finding, 546B-547Bwebsite, 96B

ApiDemos application, 40B

App Widgets

AppWidgetProvider class, 455Bcreating

application support, 453Bconfiguration activities, 455Bdimensions, 454Bproviders, 455Bsizing, 454BXML definition, 453B-454B

hosts, 460Bimplementing, 455B-456Binstalling, 460B-461Bmanifest file, configuring, 459Boverview, 452B-453Bproviders, 452Breference websites, 487Bupdate service, creating, 458B-459B

687BApp Widgets

Page 137: The Android Developer's Collection

updating, 453B, 454BonUpdate() method, 458Bupdate service, creating,

458B-459Bview hierarchies, 456B-457B

applications

activities. See activitiesAdobe AIR, building, 313BApiDemos, 40Barchitectures, 565BAVDs, creating, 51BBrowser, 302Bbuild targets, 50Bcompatibility

alternative resources. Seealternative resources

device differentiators, 523B-524Bforward, 554Bhardware configuration support,

545B-546Binternationalization, 539B-545Bmaximizing, 523B-525Buser interfaces, 525B-531Bversions, 546B-548Bwebsite, 549B

as content providers, 274Bcontent provider interfaces,

implementing, 275Bdata, adding, 278B-279Bdata columns, defining, 276Bdeleting data, 280B-281Bmanifest files, updating, 282BMIME types, returning,

281B-282Bqueries, 276B-277Bupdates, 279B-280BURIs, 276B-277B

as content type handlers, 466B-467B

Context, 70BActivity instances, 71Bapplication preferences, accessing,

70Bapplication resources, retrieving,

70Bretrieving, 70B

core files/directories, 52B-51Bdebugging

emulator, 56B-59Bon handsets, 65B-66Bregistering as debuggable, 65B

deploying, 568Bdescriptions, 87Bdeveloper competition, 21Bdevelopment. See developmentdistributing

ad revenue, 612Balternate marketplaces, 610B-611BAndroid Market, 603B-609Bbilling users, 611B-612Bconsiderations, 597B-598Bcopy protection, 611Bmanufacturer/operator

partnerships, 611Bself-distribution, 609B-610B

enhancing, 451B-452Bextending, 451B-452Bfiles, backing up, 494B-495BFlash

Adobe AIR applications, building,313B

advantages/disadvantages,311B-312B

enabling, 312B-313Bframework, 27B-28Bfree market, 22Bfunctionality, 97Bglobal searches, enabling, 478B

688B App Widgets

Page 138: The Android Developer's Collection

heap activity, monitoring, 639B-640Bhello-jni sample, 399Bicons, 87Bimages, adding, 269B

accessing images, 270B-271Bbinding data to Gallery control,

272Bdata retrieval, 272Bfinding content with URIs, 271Bgallery image retrieval, 273Bretrieved images, viewing,

273B-274Bimplementing, 567Binstalling, 593B, 651Bintegration, 21B-12Binteroperability, 451BJavaScript interface application,

308B-312BButton control click handler, 311BJavaScript control, 311BJavaScript namespace, 309BJavaScriptExtensions class, 309BonCreate() method, 309Bsample.html file JavaScript func-

tions, 310B-311Bweb page, defining, 310B

launch configurations, creating,52B-53B

location-based services, adding,62B-64B

AVDs with Google APIs, creating,62B

emulator location, configuring,62B-63B

last known location, finding,63B-64B

logging, adding, 59B-60BLunarLander, 40Bmedia, adding, 60B-62Bnames, 50B, 87B

network-driven, 565BNotePad, 40Bas operating system users, 25Bpackaging preparations

debugging, disabling, 600Bicons, 599Blogging, disabling, 600Bmanifest files for market filtering,

configuring, 599Bmarket requirements, 599B-600Bnames, 50B, 599Bpermissions, 600Btarget platforms, verifying, 599Bversions, 599B

permissions, 25BPetTracker

binding data, 253B-244Bfield names, 251BSQLiteOpenHelper class,

extending, 251B-256BPetTracker3, 270B-274Bpreferences

accessing, 70B, 231B-234Badding, 232B, 233B-234Bdata types, 231Bdeleting, 233Bfile formats, 234Bfinding, 232Bfunctionality, 232Bmethods, 233Bprivate, 232Breading, 232Bshared, 232Bupdating, 234B

projects, creating, 50Bpublishing

Android Market, 608Bcertification, 603B

689Bapplications

Page 139: The Android Developer's Collection

exporting package files, 601B-602Brelease versions, testing, 603Brequirements, 598Bsigning package files, 600B-602B

reinstalling, 651Bresources

accessing programmatically, 103Badding, 98Baliases, 123Balternative, 102B-103Banimations. See animationsBoolean, 110Bcolors. See colorsdefault, 132Bdefined, 97Bdefining types with Eclipse,

104B-107Bdimensions, 112B-113Bdirectory hierarchy, 97B-98Bdrawables, 113B-114Bimages. See imagesinteger, 111Blayout. See layoutsmenus. See menusraw files, 121B-122Breferencing, 122B-123Bretrieving, 70Bselector, 116Bstoring, 97B, 101Bstrings. See stringsstyles, 127B-130Bsystem, referencing, 131Bthemes, 131Btypes, 99B-101Bwebsite, 132BXML files, 120B-121B

responsiveness, 573B-574Brunning in Android emulator,

47B-48B, 53B-55Bsample, 40Bscreen orientation customization

example, 537B-538Bsearches, 469B-471B

activities, creating, 475B-477Benabling, 471B-472Bmanifest files, 477B-478BSearch buttons, 478BSearchable Configuration docu-

mentation website, 475Bsuggestions, 472B-474Bvoice capabilities, 474B-475Bwebsite, 487BXML configuration file, 471B

SimpleDatabasefile, accessing, 240BopenOrCreateDatabase() method,

240Bproperties, configuring, 241B

SimpleMultiTouchGesture example,516B-519B

SimpleNDK, 399B-400Bexception handling, 402B-403Bparameters, handling, 401B-402Breturn values, handling, 401B-402B

Snake, 40Badding to Eclipse workspace,

43B-44BAVD, creating, 44B-46Blaunch configurations, creating,

46B-48Brunning in Android emulator,

47B-48Bstability, 573B-574Bstand-alone, 565B

690B applications

Page 140: The Android Developer's Collection

support requirements, 568Bdocumentation, 569Bfirmware upgrades, 569Blive server changes, 569Blow-risk porting, identifying, 569Buser crash/bug reports, 569B

Sync Adapter example, 491Btesting, 567B-568Bthreads

activity, monitoring, 638B-639Bviewing, 637B-638B

uninstalling, 651Buploading applications to Android

Market, 606B-608Buser interfaces. See user interfacesversioning, 86B

AppWidgetProvider class, 455B

<appwidget-provider> tag, 454B

architectures

applications, 565Bplatform, 23B

Linux Operating System, 23B-24Bruntime environment, 25B

arcs, drawing, 219B-220B

ArcShape object, 220B

ArrayAdapter class, 194B-195B

arrays

adapters, 194B-195Bconverting to buffers, 377Bstrings, 109B-110B

ash shell, 649B

ASL/Apache2B (Apache Software License),20B

Asset Packaging tool, 98B

assets folder, 52B

asynchronous processing, 291B-293B

AsyncTask class, 292B-293B

attributes

autoLink, 136B-137BcompletionThreshold, 141Bellipsize, 136Bems, 136BFrameLayout views, 183B-185BglEsVersion, 368Bhint, 138BincludeInGlobalSearch, 478BinputType, 501Binterpolator, 230Blayouts, 181B-182BLinearLayout views, 186Blines, 138BmaxEms, 136BmaxLines, 136BmaxSdkVersion, 88BminEms, 136BminLines, 136BminSdkVersion, 88Bpermission, 95Bprompt, 144BRelativeLayout views, 187B-189Bsearch suggestions, 472BTableLayout views, 191BtargetSdkVersion, 88B, 89BtextOn/textOff, 147BTextView class, 135BView class, 127BViewGroups, 182B

audio, 346B

AudioManager service, 349Bfinding, 350Bformats website, 351Bnotifications, 431B-432Bplaying, 348B-349B, 620Brecording, 347B-348B, 619B

691Baudio

Page 141: The Android Developer's Collection

ringtones, 351Bsharing, 349B-350Bvoice searches, 474B-475Bwebsite, 351B

Audio.Albums class, 260B

Audio.Artists class, 260B

Audio.Genres class, 260B

AudioManager service, 349B

Audio.Media class, 260B

Audio.Playlists class, 260B

audioRecorder object, 348B

authenticators (accounts), 490B

auto-complete

Java code, 664Btext editors, 139B-142B

AutoCompleteTextView class, 139B

autoLink attribute, 136B-137B

automated testing, 590B

AVDs (Android Virtual Devices)

creating, 44B-46B, 51B, 616B-618Bemulator

configuring, 616B-617Blaunching, 623Bphone call simulation, 625Bsettings, configuring, 615B-616B

Google APIs, 319Bhardware options, 618B-620BManager, 36B-37Bskin options, 618B

Bbackup agents

implementing, 492B-493Bregistering, 495B-496B

backup services, 491B

application files, 494B-495Barchived data, wiping, 655B

backup agentsimplementing, 492B-493Bregistering, 495B-496B

controlling with ADB, 654B-655Bforcing restores, 655Bremote, choosing, 492Brequesting backups, 496Brestore operations, 496B-497Bscheduling, 655Bshared preferences files, 493B-494Btroubleshooting, 497Bwebsite, 497B

BackupAgentHelper class, 492B

backward compatibility

Java Reflection, 547B-548Bwithout reflection website, 548B

basic buttons, 144B-146B

BasicGLThread class, 372B

batteries

AVD hardware option, 619Bmonitoring, 417B-420B

BatteryManager class, 419B

beginTransaction() method, 244B

benefits, 18B

best practices

designAndroid Developers blog, 574Bbilling and revenue generation,

575Bnetwork diagnostics, 576B-577Bresponsiveness, 573B-574Brules, 571B-572Bsilly mistakes, avoiding, 578Bstability, 573B-574Bthird-party standards, 576Btools, 578Bupdates/upgrades, 577B-578B

692B audio

Page 142: The Android Developer's Collection

user demands, meeting, 572Buser interfaces, 572B-573B

development, 579Bcode diagnostics, 581Bcode quality, 580Bcode reviews, 581Bcoding standards, 580B-581Bdevice specific bugs, 582Bfeasibility testing, 579B-580Bsilly mistakes, avoiding, 583Bsoftware processes, 579Btools, 583Bunit testing, 581B-582B

emulator, 613B-614Bsecurity, 574B

handling private data, 575Btransmitting private data, 575B

testing, 585Bapplication installations, 593Bautomation, 590Bbackup services, 594Bbilling, 594Bblack box, 591Bbuild acceptance tests, 589Bconformance, 593Bcoverage, maximizing, 589Bdefect tracking systems, 585B-587Bdevice fragmentation, 587Bemulator limitations, 590B-591Bemulator versus actual device,

589B-590Benvironments, 587Bintegration points, 592B-593Binternationalization, 593Boutsourcing, 596Bperformance, 594Bpreproduction devices, 590Bpriorities, 588B

quality, 594Breal-life device configurations,

588Bservers, 591B-592Bservices, 591B-592Bsilly mistakes, avoiding, 595Bsignal loss, 589Bsoftware integration, 588B-589Bspecialized scenarios, 592Bstarting states, 588Bthird-party firmware, 587Bthird-party standards, 592Btools, 595Bunexpected events, 594Bupgrades, 593Busability, 592Bwhite box, 591B

websites, 584Bbilling users, 611B-612B

generation methods, 575Btesting, 594B

bindService() method, 438B

Bitmap class, 212B

BitmapDrawable class, 116B

bitmaps, 212B

Bitmap class, 212Bdrawing, 213Bscaling, 213Btransforming into matrixes, 213B

black box testing, 591B

blinking light notifications, 430B-431B

clearing, 431Bcolors, 430Bcustomizing, 431Bprecedence, 430Btesting, 430Burgency, 430B-431B

693Bblinking light notifications

Page 143: The Android Developer's Collection

Bluetooth

available, finding, 415Bclasses, 415Bconnections, 416B-417Bdevice discovery, 416Benabling, 415B-416Bfunctionality, 414Bimplementation example, 417B-418Bpaired devices, querying, 416Bpermissions, 415Bwebsites, 421B

BluetoothAdapter class, 415B

BluetoothDevice class, 415B

BluetoothServerSocket class, 415B

BluetoothSocket class, 415B

Bodlaender, Hans, 211B

bold strings, 108B

<bool> tag, 110B

Boolean resources, 110B

Borland SilkTest, 589B

BounceInterpolator, 230B

boundCenterBottom() method, 330B

broadcasting

intents, 79Breceivers, registering, 93B-94B

broadcastIntent() method, 79B

Browser application, 259B, 263B, 302B

accessing, 263Bquerying for most visited bookmarked

sites, 263B-264Bbrowser images, downloading, 271B

browsing the Web, 301B-302B

chrome, adding, 305B-307Bevent handling, 304B-305BFlash support

Adobe AIR applications, building,313B

advantages/disadvantages,311B-312B

enabling, 312B-313BJavaScript, enabling, 304Bmouseovers, 304Bsettings, configuring, 304BWebKit rendering engine, 301B

android.webkit package, 307Bclasses, 307Bfunctionality, 308BJavaScript interface application,

308B-312BOpen Source Project website, 314Bsupport, 307B

zooming, 304Bbuffers, 377B

bugs

device specific, 582Breports, 569B, 655B-656Bresolution process website, 32B

build acceptance tests, 589B

build errors, resolving, 667B

build targets, 50B

built-ins

content providers, 259Blayouts, 181Bthemes, 171Bview containers, 193B

Bundle objects, 75B

BusyBox

binary, installing, 660Bwebsites, 660B

Button class, 144B

buttons, 144B

basic, 144B-146Bcheck boxes, 144B, 146B-147Bimages, 146B

694B Bluetooth

Page 144: The Android Developer's Collection

margin example, 183Bradio, 144B, 148B-149BSearch, 478Btoggles, 144B, 147B

CC2DM (Cloud to Device Messaging), 438B

cache files

AVD hardware option, 620Bcreating, 238B-239Bretrieving, 236B

CacheManager class, 307B

calculateAndDisplayFPS() method, 385B

calibrating device sensors, 410B-411B

call states

listening for changes, 355Bpermissions, 354Bquerying, 354B-355Broaming, 356Bservice state, 355B-356B

CallLog content provider, 259B, 261B-263B

access permissions, 262B-263Btagging phone numbers with custom

labels, 262Bcamera

AVD hardware option, 619Bimage capturing, 336B-340B

adding, 336B-337Bbutton click handler, 340BCamera object, instantiating,

337B-338Bcamera parameters, 338BCameraSurfaceView class, 337Blayouts, 339Bstarting preview, 338B-339Bstopping preview, 338BtakePicture() method, 339B

settings, configuring, 340B-341Bzoom controls, 341B

Camera class, 340B

CameraSurfaceView class, 337B

cancel() method, 428B

cancelDiscovery() method, 416B

canDetectOrientation() method, 521B

canvases, 205B-207B

bitmaps, drawing, 213BCanvas object, 207Bdimensions, 207Bred circle on black canvas example,

205B-206Bcellular networks, emulating, 298B

certifying applications, 603B

change listeners

call states, 355Bentire screen events

GlobalFocusChange events, 163BGlobalLayout events, 163BPreDraw events, 163B

entire screen events, listening,162B-163B

focus changes, 164B-165Btouch mode changes, 161B-162B

character picker dialogs, 165B

check boxes, 144B, 146B-147B

chess font, 211B

child views, 178B

choosing

build targets, 50Bdevices for device databases, 556BIDEs (integrated development

environments), 20Bpaint colors, 207Bprogramming languages, 26Bremote backup services, 492B

695Bchoosing

Page 145: The Android Developer's Collection

SDK versionsmaximum, 90Bminimum, 89Btarget, 89B

software keyboards, 500B-502Bsource control systems, 563B-564Btarget markets, 568Bversioning systems, 564B

Chronometer class, 155B-156B

circles, drawing, 219B

classes

AbsoluteLayout, 190BAbstractAccountAuthenticator, 490BAbstractThreadedSyncAdapter, 491BAccountManager, 490B, 497BActivity, 71BAdapterView

ArrayAdapter class, 194B-195Bbinding data, 196BCursorAdapter class, 195B-196Bevent handling, 197B

AnalogClock, 156B-157BAnimationUtils, 227B-228BAppWidgetProvider, 455BArcShape, 220BArrayAdapter, 194B-195BAsyncTask, 292B-293BaudioRecorder, 348BAutoCompleteTextView, 139BBackupAgentHelper, 492BBasicGLThread, 372BBatteryManager, 419BBitmap, 212BBitmapDrawable, 116BBluetooth, 415BBundle, 75BButton, 144BCacheManager, 307B

Camera, 340BCameraSurfaceView, 337BCanvas, 207BChronometer, 155B-156BConfiguration, 544BConnectivityManager, 297BConsoleMessage, 307BContactsContract, 264BContentValues, 268BContentResolver, 276BContext class, 70B

Activity instances, 71Bapplication preferences, accessing,

70Bapplication resources, retrieving,

70Breference website, 80Bretrieving, 70B

ContextMenu, 159B-161BCookieManager, 307BCursorAdapter, 195B-196BCustomGL2SurfaceView, 392BCustomRenderer, 392BDatePicker, 150B-151BDialog, 165BDigitalClock, 156BDisplayMetrics, 526BEditText, 138B-142B

auto-complete, 139B-142Bdefining, 138Binput filters, 142Blong presses, 138B-140B

FileBackupHelper, 494B-495BGallery, 178BGalleryView, 194BGameAreaView

defining, 511Bmethods, 511B, 513B

696B choosing

Page 146: The Android Developer's Collection

multi-touch gestures, 516B-519Bsingle-touch gestures, 510B-513B

Geocoder, 319Baddress line queries, 320Bnamed locations, 320B-322Bspecific information queries, 320B

GeomagneticField, 412BGeoPoint, 324BGestureDetector, 509B

interfaces, 510Bsingle-touch gesture support,

509B-510BGestureOverlayView, 509Bgestures, 509BGLDebugHelper, 373BGLES20, 392BGLSurfaceView

functionality, 388Bimplementing, 375B-390B

GPS satellite, 333BGPXService, 439BGridView, 194BHandler, 384BHorizontalScrollView, 201BHttpURLConnection, 289BInputMethodManager, 502BIntent, 78BItemizedOverlay, 329B-332B, 333BJava, creating, 664BJavaScriptExtensions, 309BJNIEnv, 402BLayoutParams, 182BLinearGradient, 208BLinearInterpolator 230BListView, 178B, 194B, 197B-198BLocationListener, 316BLocationManager, 316B

Logimporting, 59Bmethods, 59B

MapController, 324BMarginLayoutParams, 182BMatrix, 213BMediaPlayer, 60B

audio, playing, 348B-349Bmethods, 61Bvideo, 346B

MediaRecorderaudio, 347B-348Bvideo, 343B-345B

MediaScannerConnection, 342BMediaStore content provider, 260BMotionEvent, 509BMultiAutoCompleteTextView, 141BNativeBasicsActivity.java, 400BNotificationManager, 425B, 435BOnRatingBarChangeListener, 155BOrientationEventListener, 520BOvalShape, 219BPaint, 207BParcelable, implementing, 446B-449BPath, 220B-222BPrefListenerService, 458BProgressBar class, 151B-153BRadialGradient, 209BRatingBar class, 154B-155BRecognizerIntent, 504B-505BRectShape, 216BRemoteViews, 456B-457BRenderer

functionality, 388Bimplementing, 375B-390B

RestoreObserver, 496B-497BRingtoneManager, 351B

697Bclasses

Page 147: The Android Developer's Collection

RotateAnimation, 229BRoundRectShape, 217BScaleAnimation, 229BScaleGestureDetector

multi-touch gestures, 516Bnavigational gestures, 509B

ScanResult, 413BScrollView, 201BSearchManager, 470BSeekBar, 153B-154BSensor, 408BSensorEvent, 410BSensorManager, 408BService, 439B, 449BServiceConnection, implementing,

445B-446Bshapes, 214BSharedPreferencesBackupHelper, 493BSimpleDataUpdateService, 458BSimpleOnGestureListener, 510BSimpleOrientationActivity,

520B-521BSimpleViewDetailsActivity, 468BSlidingDrawer, 202B-203BSmsManager

divideMessage() method, 362BgetDefault() method, 358B

Spinner, 143B-144BSQLite

databases, managing, 239Bdeleting, 249B

SQLiteDatabase, 246B-247BSQLiteOpenHelper, 250B,

251B-252BSQLiteQueryBuilder, 248B-249BSweepGradient, 209BTabActivity, 198B-200BTabHost, 178B, 198B

creating tabs from scratch,200B-201B

TabActivity class implementation,198B-200B

TelephonyManager, 354BTextView, 134B-138B

contextual links, creating,136B-138B

height, 136Bretrieving, 126Bstyles, applying, 169Btext attribute, 135Bwidth, 136B

TimePicker, 151BTranslateAnimation, 230BUri, 61BUriMatcher, 277B-278BURL, 288BURLUtil, 307BView. SeeView classViewGroups, 178B

attributes, 182Bchild View objects, adding, 178Blayout classes, 178Bsubclass categories, 178BView container controls, 178B

ViewSwitcher, 202BViewTreeObserver

OnGlobalFocusChangeListenerinterface, 163B

OnGlobalLayoutListener, 163BOnPreDrawListener interface,

163BOnTouchModeChangeListener

interface, 162BViewWithRedDot, 205B-206BWallpaperManager, 342BWallpaperService, 462B

698B classes

Page 148: The Android Developer's Collection

WebBackForwardList, 307BWebChromeClient, 305B-307BWebHistoryItem, 307BWebKit rendering engine, 307BWebSettings, 304BWebView. See also WebKit rendering

enginebenefits, 307Bchrome, adding, 305B-307Bcontent, loading, 302B-304Bevent handling, 304B-305Blayouts, designing, 302Bsettings, configuring, 304BWeb browsing, 301B-302B

WebViewClient, 304B-305BWifiManager, 412B-413B

clear() method, 233B

clearing logs, 654B

click events, handling

AdapterView controls, 197Bbasic button controls, 146Bimage capturing, 340Blong clicks, 164Bmenu option selection

context menus, 161Boptions menus, 159B

client-server testing, 562B

clock controls, 156B-157B

close() method, 250B

closing SQLite databases, 250B

cloud computing Wikipedia website, 497B

Cloud to Device Messaging (C2DM), 438B

code. See also development

diagnostics, 581Bquality, 580Breviewing, 581Bstandards, 580B-581Bunit testing, 581B-582B

code obfuscation tools, 611B

collapseColumns attribute, 191B

colors, 111B-112B

# (hash symbol), 111Bblinking light notifications, 430Bformats, 111Bpaints, 207B

antialiasing, 207Bchoosing, 207Bgradients, 207B-208Blinear gradients, 208BPaint class, 207Bradial gradients, 209Bstyles, 207Bsweep gradients, 209B

resource file example, 111Bvertices (3D graphics), 377B-378B

<color> tag, 111B

command-like gestures, 509B

commit() method, 234B

compare() method, 357B

compatibility

alternative resources. See alternativeresources

device differentiators, 523B-524Bforward, 554Bhardware configuration support,

545B-546Binternationalization, 539B-545B

default language, configuring,541B-543B

language alternative resources,540B-542B

locales, 544B-545Btesting, 593B

maximizing, 523B-525Buser interfaces, 525B-531B

Nine-Patch Stretchable images,526B-528B

699Bcompatibility

Page 149: The Android Developer's Collection

screen support, 526Bworking square principle,

528B-531Bversions, 546B-548B

API levels, finding, 546B-547Bbackward compatibility with Java

Reflection, 547B-548Bwebsite, 549B

completionThreshold attribute, 141B

complex queries (SQL), 248B-249B

Configuration class, 544B

configuring

alternative resources, 538BApp Widget manifest file, 459BAVDs (Android Virtual Devices),

616B-617Bcamera settings, 340B-341Bemulator locations, 62B-63B,

623B-624Bintent filters, 93Blanguages, 541B-543Blive wallpaper manifest file,

464B-465Bmanifest files for market filtering,

599Bmultimedia optional features,

335B-336Boperating system for debugging, 30BOpenGL ES 2B.0B, 391Bplatform requirements, 90B-92B

device features, 91Binput methods, 90Bscreen sizes, 91B-92B

SQLite database properties, 241Bsystem requirements, 87B-90B

conformance, testing, 593B

connections

services, 438Bspeeds, monitoring, 356B-357B

ConnectivityManager class, 297B

console (Emulator)

commands, 632Bconnections, 628BGPS coordinates, 630Bincoming call simulations, 628B-629Bnetwork status, monitoring, 631Bpower settings, 631BSMS message simulation, 629B-630B

ConsoleMessage class, 307B

Contacts content provider, 259B, 264B

private data, accessing, 264B-266Bquerying, 266B-267Brecords

adding, 267B-268Bdeleting, 269Bupdating, 268B-269B

ContactsContract class, 264B

containers (views), 193B

adapters, 194Barrays, 194B-195Bbinding data, 196Bcursor, 195B-196Bevent handling, 197B

galleries, 194Bgrids, 194Blists, 194B, 197B-198Bscrolling support, 201Bsliding drawers, 202B-203Bswitchers, 202Btabs, 198B

creating from scratch, 200B-201BTabActivity class implementation,

198B-200Bcontains() method, 233B

content providers

adding images to applications, 269Baccessing images, 270B-271B

700B compatibility

Page 150: The Android Developer's Collection

binding data to Gallery control,272B

data retrieval, 272Bfinding content with URIs, 271Bgallery image retrieval, 273Bretrieved images, viewing,

273B-274Bapplications as, 274B

data, adding, 278B-279Bdata columns, defining, 276Bdeleting data, 280B-281Binterfaces, implementing, 275Bmanifest files, updating, 282BMIME types, returning,

281B-282Bqueries, 276B-277Bupdating, 279B-280BURI pattern matching, 277B-278BURIs, defining, 276B

Browser, 259B, 263Baccessing, 263Bquerying for most visited

bookmarked sites, 263B-264Bbuilt-in, 259BCallLog, 259B, 261B-263B

access permissions, 262B-263Btagging phone numbers with

custom labels, 262BContacts, 259B, 264B

adding records, 267B-268Bdeleting records, 269Bprivate data, accessing, 264B-266Bquerying, 266B-267Bupdating records, 268B-269B

dataadding, 267B-268Bdeleting, 269B

retrieving, 272Bupdating, 268B-269B

interfaces, implementing, 275Blive folder

enabling, 283Bprojections, 284Bqueries, handling, 482B-484BURIs, defining, 283B-284B

MediaStore, 259B, 260Bclasses, 260Bdata requests, 260B-261B

permissions, 95Bregistering, 94BSettings, 259B, 267BUserDictionary, 259B, 267Bwebsite, 285B

content type handlers, 466B-467B

ContentResolver class, 276B

ContentValues class, 268B

Context class, 70B

Activity instances, 71Bapplication preferences, accessing, 70Bapplication resources, retrieving, 70Breference website, 80Bretrieving, 70B

context menus, enabling, 159B-161B

ContextMenu class, 159B-161B

contextual links, creating, 136B-138B

controls, 134B. See also classes

buttons, 144Bbasic, 144B-146Bcheck boxes, 144B, 146B-147Bradio, 144B, 148B-149Btoggles, 144B, 147B

clocks, 156B-157Bhardware for debugging, 30B-31Blayout, 134B

701Bcontrols

Page 151: The Android Developer's Collection

OptionsMenu, 157B-159Bprogress bars

Chronometer class, 155B-156BRatingBar class, 154B-155BSeekBar class, 153B-154B

progress indicators, 151B-153Bservices, 443B-444Bsource control systems, 563B-564B

choosing, 563B-564BEclipse IDE integration, 661B

CookieManager class, 307B

copy protection, 611B

copying files

ADB commands, 650BDDMS File Explore, 641B-642B

/core files/directories, 52B-51B

crash reports, 569B

createBitmap() method, 213B

createScaledBitmap() method, 213B

createTabContent() method, 200B

credentials (accounts), 490B

cubes, drawing, 378B

cursors

CursorAdapter class, 195B-196BSQLite databases, querying, 245B

custom binaries, installing, 659B-660B

CustomGL2SurfaceView class, 392B

customization method (project requirements), 554B

customizing

blinking light notifications, 431Bdialogs, 168Bfonts, 211B-212Blocales, 544Blog filters, 663Bnotifications, 432B

layouts, 433B-434Btext, 432B-433B

screen orientation example,537B-538B

software keyboards, 502BCustomRenderer class, 392B

CycleInterpolator, 230B

Cygwin website, 398B

DDalvik

Debug Monitor Server. See DDMSpackages, 35Bvirtual machine, 25B

data synchronization, 491B, 497B

/data/app directory, 641B

databases

devicesdata storage, 556Bdevices, choosing, 556Bfunctionality, 558Bmanaging, 555B-557Bthird-party, 558B

persistent, creating, 250BSQLite. See SQLite databasesstudent grade example, 675B-682B

adding data to tables, 677Bcalculated columns, 680B-682Bdeleting tables, 682Bediting, 679Bforeign keys, 678B-679Bmultiple queries, 680Bpurpose, 675B-676Bquerying, 677B-678Bschema, 676BStudents table, 676BTests table, 676Bupdating, 679B

dataChanged() method, 496B

702B controls

Page 152: The Android Developer's Collection

/data/data/<package name>/cache/ directory, 641B

/data/data/<package name>/databasesdirectory, 641B

/data/data/<package name> directory,641B

/data/data/<package name>/files/ directory, 641B

/data/data/<package name>/shared_prefs/ directory, 641B

date input retrieval, 150B-151B

date picker dialogs, 165B

DatePicker class, 150B-151B

DDMS (Dalvik Debug Monitor Server),36B, 38B

application threadsactivity, monitoring, 638B-639Bviewing, 637B-638B

availability, 635Bdebuggers, attaching, 638BEclipse Perspective, 636BEmulator Control tab

functionality, 642B-643Blocation fixes, 643BSMS message simulation, 643Bvoice calls, simulating, 643B

features, 636B-637BFile Explorer

browsing, 641Bcopying files, 641B-642Bdeleting files, 642Bdirectory listing, 641Bdrag-and-drop support, 642B

garbage collection, 639Bheap activity, monitoring, 639B-640BLogCat utility, 644Bmemory allocation, 640Bprocesses, stopping, 640Bscreen captures, 645B

stand-alone tool, 636Bwebsite, 38B

debugging

ADB (Android Debug Bridge). SeeADB

applications, 56B-59Bbugs

device specific, 582Breports, 569B, 655B-656Bresolution process website, 32B

configurations, creating, 53Bon handsets, 65B-66Bhardware configuration, 30B-31Boperating system configuration, 30Bregistering applications as debuggable,

65BSDK, 32Buser interfaces, 180BView object drawing issues, 180B

DecelerateInterpolator, 230B

default.properties file, 52B

default resources, 132B

defect tracking systems

defectsdefining, 586B-587Binformation, logging, 585B-586B

designing, 585Bdelete() method

contacts, 269Bcontent provider data, 280B-281B

deleteFile() method, 235B

deleting

Android Market applications, 609Bcontent provider data, 269B,

280B-281Bdialogs, 167Bfiles, 235B, 642Bpreferences, 233B

703Bdeleting

Page 153: The Android Developer's Collection

SQLite database records, 243B-244Bobjects, 249B

wallpapers, 343Bdeploying applications, 568B. See also

distributing applications

designing

Android Developers blog, 574Bbest practices

billing and revenue generation,575B

network diagnostics, 576B-577Bresponsiveness, 573B-574Bstability, 573B-574Bthird-party standards, 576Bupdates/upgrades ease, 577B-578Buser demands, 572Buser interfaces, 572B-573Bwebsites, 584B

extensibility, 565B-566Bhandsets, 16Binteroperability, 566B-567Blayouts, 125B-127Blocale support, 544B-545Bmaintenance, 565B-566Bnotifications, 434Brules, 571B-572Bsecurity, 574B

handling private data, 575Btransmitting private data, 575B

silly mistakes, avoiding, 578Btools, 578B

destroying Activities, 75B

developers

accountsbenefits, 609Bcreating, 26B, 604B-606B

Distribution Agreement, 604B

development

best practices, 579Bcode diagnostics, 581Bcode quality, 580Bcode reviews, 581Bcoding standards, 580B-581Bdevice specific bugs, 582Bfeasibility testing, 579B-580Bsoftware processes, 579Bunit testing, 581B-582Bwebsites, 584B

common packages, 27BEclipse IDE. See Eclipse IDEenvironment, testing, 43B

adding projects to Eclipse workspace, 43B-44B

AVDs, creating, 44B-46Blaunch configurations, creating,

46B-48Brunning applications in Android

emulator, 47B-48Bframework, 27B-28Bhardware configuration, 30B-31Bhistory, 17B-18Bmobile software

acquiring target devices, 560Bapplications, implementing, 567Barchitectures, 565Bdeployment, 568Bdevice databases, 555B-558Bdevice limitations, 561B, 564Bextensibility, 565B-566Binteroperability, 566B-567Biteration, 553B, 570Bmaintenance, 565B-566Boverview, 551Bproject documentation, 562B-563Bproject requirements, 553B-554B

704B deleting

Page 154: The Android Developer's Collection

quality assurance risks, 561B-562BRapid Application Development

website, 570Bsource control systems, choosing,

563B-564Bsupport requirements, 568B-569Btarget device identification,

558B-560Btesting, 567B-568Bthird-party requirements, 555Buse cases, 555Bversioning systems, choosing, 564Bwaterfall approaches, 552B, 570BWikipedia website, 570B

native versus third-party, 27Boperating system configuration, 30Bprogramming languages, 26BSDK upgrades, 31Bsilly mistakes, avoiding, 583Bsoftware requirements, 29Bsystem requirements, 29Btools, 578B, 583B

devices

acquiring, 560BADB commands, 648Bbattery monitoring, 417B-420BBluetooth

connections, 416B-417Bdiscovery, 416Bpaired devices, querying, 416B

bugs, handling, 582Bcompatibility

alternative resources. Seealternative resources

differentiators, 523B-524Bforward, 554Bhardware configuration support,

545B-546B

internationalization, 539B-545Bmaximizing, 523B-525Buser interfaces, 525B-531Bversions, 546B-548Bwebsite, 549B

connected, listing, 647B-648Bconvergence, 13Bcustom binaries, installing, 659B-660Bdatabases

data storage, 556Bdevices, choosing, 556Bfunctionality, 558Bmanaging, 555B-557Bthird-party, 558B

debugging applications, 65B-66Bdefect tracking systems, 585B

defect information, logging,585B-586B

defects, defining, 586B-587Bfeatures, configuring, 91Bfiles

browsing, 641Bcopying, 641B-642B, 650Bdeleting, 642B

fragmentation, 587Bhardware

accessing, 407Bemulator support, 408Bfeatures, 408B

identifying, 558B-560Bindicator lights, 430Blanguages, configuring, 541B-543Blimitations, 561B, 564Blocations, finding, 316B-318Bmanufacturers, 16B

customizations, 559Bdistribution partnerships, 611B

705Bdevices

Page 155: The Android Developer's Collection

market availability, 559B-560Bmobile operators, 17BNexus One and Android Dev Phones

website, 570Bnotifications support, 424BOpenGL ES compatibility,

368B-369Bpreproduction, testing, 590BRAM size AVD hardware option,

619Breal-life configurations, 588Bscreen captures, 645Bsensors, 408B

accelerometer, 410B-411Baccessing, 408B, 409Bavailability, 409Bcalibrating, 410B-411Bdata, reading, 409B-410Bmost common, 408B-409Borientations, 411B-412BSensor Simulator, 409Btesting, 409Btrue north, finding, 412B

Dialog class, 165B

dialogs, 165B

adding to activities, 166B-167Balert, 165Bcharacter picker, 165Bcustomizing, 168Bdate picker, 165Bdefining, 167BDialog class, 165Bdismissing, 167Binitializing, 167Blaunching, 167Blifecycle, 166B-167Bprogress, 165B

removing, 167Btime picker, 166Btypes, 165B-166B

DigitalClock class, 156B

<dimen> tag, 112B

dimensions, 112B-113B

App Widgets, 454Bcanvases, 207Bresource file example, 113Bretrieving, 113Bunit measurements, 112B

directories, 235B. See also files

alternative resource qualifiersAndroid platform, 536Bapplying, 532B-537Bbad examples, 536B-537Bcase, 532Bcombining, 532Bdefault resources, 536Bdock mode, 534Bgood examples, 536Bkeyboard type and availability, 535Blanguage and region code, 533Bmobile country code, 533Bmobile network code, 533Bnames, 532Bnavigation key availability, 535Bnavigation method, 536Bnight mode, 534Brequired strings, 533Bscreen aspect ratio, 534Bscreen orientation, 534Bscreen pixel density, 534Bscreen size, 533Btext input method, 535Btouch screen type, 535B

706B devices

Page 156: The Android Developer's Collection

cache filescreating, 238B-239Bretrieving, 236B

core, 52B-51B/data/app, 641B/data/data/<package name>, 641B/data/data/<package name>/cache/,

641B/data/data/<package name>/

databases, 641B/data/data/<package name>/files/,

641B/data/data/<package name>/

shared_prefs/, 641Bfiles

creating, 236B, 238Breading, 236Breading byte-by-byte, 237Bretrieving, 236B, 238BXML, 237B

listing of, 641B/mnt/sdcard, 641B/mnt/sdcard/download/, 641Bresources, 97B-98Bretrieving, 236B

dismissDialog() method, 166B, 167B

dismissing dialogs, 167B

display characteristics, finding, 526B

DisplayMetrics class, 526B

distributing applications, 568B. See alsopublishing applications

ad revenue, 612Balternate marketplaces, 610B-611BAndroid Market, 603B-609B

country requirements, 604Bdeleting applications, 609Bdeveloper accounts, 604B-606B,

609B

Developer Distribution Agreement,604B

help, 607Blicensing service, 604Bpublication, 608Brefund policy, 608B-609Bsign-up website, 604Bupgrading applications, 609Buploading applications, 606B-608Bwebsite, 612B

billing users, 611B-612Bgeneration methods, 575Btesting, 594B

considerations, 597B-598Bcopy protection, 611Bmanufacturer/operator partnerships,

611Bself-distribution, 609B-610B

divideMessage() method, 362B

dock mode alternative resource qualifier,534B

documentation

Javadoc-Style documentation, 667Bmaintaining, 569Bporting, 563BSDK, 33B-34BSearchable Configuration

documentation website, 475Bsoftware development, 562B-563B

quality assurance plans, 562B-563Bthird-party, 563B

third-party, 563Buser interfaces, 563B

doInBackground() method, 292B

doStartService() method, 441B

downloading images from browsers, 271B

DPad AVD hardware option, 619B

Draw Nine-patch tool, 40B, 527B-528B

707BDraw Nine-patch tool

Page 157: The Android Developer's Collection

<drawable> tag, 114B

drawables, 113B-114B

drawBitmap() method, 213B

drawFrame() method, 404B

drawing

3D graphicscoloring vertices, 377B-378Bcubes, 378Blighting, 379B-382Btexturing, 381B-384Bvertices, 376B-377B

android.graphics package, 230Banimations

android.view.animation package,226B

frame-by-frame, 223B-225Binterpolators, 230Bloading, 227B-228Bmoving, 229B-230Brotating, 228B-229Bscaling, 229Btransparency, 228Btweening. See tweening animationstypes, 221B-223B

bitmaps, 212B, 213BBitmap class, 212Bscaling, 213Btransforming into matrixes, 213B

canvases, 205B-207BCanvas object, 207Bdimensions, 207B

paints, 207B-210Bantialiasing, 207Bcolors, choosing, 207Bgradients, 207B-208Blinear gradients, 208BPaint class, 207B

radial gradients, 209Bstyles, 207Bsweep gradients, 209Butilities, 210B

red circle on black canvas example,205B-206B

shapesarcs, 219B-220Bclasses, 214Bdefining as XML resources,

214B-215Bdefining programmatically,

215B-216Bovals/circles, 219Bpaths, 220B-222Bround-corner rectangles,

217B-218Bsquares/rectangles, 216B-217Bstars, 221B-222B

triangles on the screen, 375B-376B

EEclipse IDE, 30B

auto-complete, 664Bbuild errors, resolving, 667Bdownload website, 29BJava code

classes, creating, 664Bformatting, 664Bimports, organizing, 664B-665Bmethods, creating, 664B

Javadoc-Style documentation, 667Blayouts, designing, 125B-127Blog filters, creating, 663Bmanifest files, editing, 82Bmultiple file sections, viewing, 662Bperspectives, 56B, 662BPlug-In, 35B

708B <drawable> tag

Page 158: The Android Developer's Collection

projects, adding, 43B-44Brefactoring code, 665B

Extract Local Variable tool, 666BExtract Method tool, 666B

Rename tool, 665Breorganizing code, 667Bresources, defining, 104B-107BSimpleNDK application, 399B-400B

exception handling, 402B-403Bnative code from Java, calling,

400B-401Bparameters, handling, 401B-402Breturn values, handling, 401B-402B

source control services integration,661B

tabsrepositioning, 661B-662Bunwanted, closing, 662B

website, 41Bwindows

maximizing, 662Bminimizing, 662Bopen, limiting, 663Bside by side view, 662B

edit() method, 233B

editing

manifest files, 82Bapplication-wide settings, 83B-84BEclipse, 82Bmanually, 84B-86Bpackage-wide settings, 82B-83Bpermissions, 83Btest instrumentation, 83B

strings, 107BEditText class, 138B-142B

auto-complete, 139B-142Bdefining, 138B

input filters, 142Blong presses, 138B-140B

EGL, initializing, 373B-374B

eglDestroyContext() method, 387B

eglDestroySurface() method, 387B

eglMakeCurrent() method, 387B

eglTerminate() methods, 387B

elapsedRealtime() method, 156B

ellipsis (…), 136B

ellipsize attribute, 136B

emergency phone numbers, 357B

ems attribute, 136B

emulator, 37B-38B

actual device testing, compared,589B-590B

AVDs (Android Virtual Devices),615B-616B

configuring, 616B-617Bcreating, 616B-618Bhardware options, 618B-620Bskin options, 618B

best practices, 613B-614Bblinking lights, 430Bconnected, listing, 647B-648Bconsole

commands, 632Bconnections, 628BGPS coordinates, 630Bincoming call simulations,

628B-629Bnetwork status, monitoring, 631Bpower settings, 631BSMS message simulation,

629B-630Bcustom binaries, installing, 659B-660BDDMS Emulator Control tab

functionality, 642B-643Blocation fixes, 643B

709Bemulator

Page 159: The Android Developer's Collection

SMS message simulation, 643Bvoice calls, simulating, 643B

debugging applications, 56B-59Bfiles

browsing, 641Bcopying, 641B-642B, 650Bdeleting, 642B

fun tips, 632Bhardware support, 408Blaunching, 620B-623B

running applications, 621B-623BSDK and AVD Manager, 623Bstartup options, 621B

limitations, 590B-591B, 632B-633Blocation, configuring,

62B-63B, 318B, 623B-624Bmessaging between, 625B-628Boverview, 613Bphone call simulation, 625Brunning applications through,

47B-48B, 53B-55Bscreen captures, 645Bstarting/stopping, 649B-650Bvibration, 429Bwebsite, 38BWiFi testing, 414B

enhancing applications, 451B-452B

entire screen event handling, 162B-163B

GlobalFocusChange, 163BGlobalLayout, 163BPreDraw, 163B

event handling

AdapterView controls, 197Bbutton clicks

basic button controls, 146Bimage capturing, 340B

entire screen events, 162B-163BGlobalFocusChange, 163BGlobalLayout, 163BPreDraw, 163B

focus changes, 164B-165Blive wallpapers, 463Blong clicks, 164Bmenu option selection

context menus, 161Boptions menus, 159B

screen orientation changes,520B-521B

touch mode changes, 161B-162BWebView class, 304B-305B

execSQL() method, 241B

Exerciser Monkey command-line tool, 594B,596B

database data, 672Bpackage files, 601B-602B

extending applications, 451B-452B

extensibility designs, 565B-566B

Extensible Markup Language. See XML

external Activities, launching, 77B

external libraries, 92B

Extract Local Variable tool, 666B

Extract Method tool, 666B

Extras property, 78B

extreme programming website, 570B

Ffeasibility testing, 579B-580B

FileBackupHelper class, 494B-495B

fileList() method, 236B

files. See also directories

application, backing up, 494B-495Bbrowsing, 641B

710B emulator

Page 160: The Android Developer's Collection

cacheAVD hardware option, 620Bcreating, 238B-239Bretrieving, 236B

copyingADB commands, 650BDDMS File Explore, 641B-642B

core, 52B-51Bdatabase formats, 669Bdeleting, 235B, 642Bimage extensions, 114B-115Blisting, 236Blocations, 50Bmanifest. See manifest filesopening, 235Bpackages, signing/exporting,

601B-602Bpreferences, 231B-234Braw, 121B-122Bresource, storing, 97Bshared preferences, backing up,

493B-494BSQL script files, creating, 673Bstoring, 101B, 235BXML

App Widget definitions,453B-454B

attributes, 120Bin-application search files, 471Blayouts, 120B-121B, 126B,

173B-175Blive wallpaper definition, 464Bparsing, 290B-291Bservices permissions file, 443Bshapes, defining, 214B-215BSMS permissions, 358Btelephony state information, 354Btweened animations, defining, 226Butility packages, 237B

filter() method, 142B

filters

input, 142Bintents

configuring, 93Bcreating, 77Bprimary entry point activities,

92B-93Bregistering, 469Bremote interfaces, implementing,

446Blogging, 652B-653Bmarket, 599B, 612B

finding

API levels, 546B-547Baudio, 350Bcontent with URIs, 271Bdevice locations, 316B-318Bdisplay characteristics, 526Blast known location, 63B-64Bmultimedia, 350Bpreferences, 232Btrue north, 412B

finish() method, 76B

firmware upgrades, 569B

first generation mobile phones, 9B-10B

first-to-market advantages, 23B

Flash applications

Adobe AIR applications, building,313B

advantages/disadvantages, 311B-312Benabling, 312B-313B

fling gestures, 515B

focus changes, handling, 164B-165B

folders

assets, 52Bgen, 52B

711Bfolders

Page 161: The Android Developer's Collection

live, 282Bactivities, 282B, 481B-482Bcomponents, 282B-283Bcontent provider queries,

482B-484Bcreating, 481Benabling, 283Binstalling, 485B-486Blist with dates example, 285Bmanifest files, configuring, 484Boverview, 480Bpicker information, 484Bprojections, 284BURIs, defining, 283B-284Bwebsite, 487B

res, 52Bres/drawable-*/icon.png, 52Bsrc, 52B

fonts

chess font, 211Bcustomizing, 211B-212Bdefault, 210Bitalic, 210BMonotype example, 210BSans Serif example, 210BsetFlags() method, 211Bsupport, 210B-211B

forceError() method, 56B

foreground attribute, 183B

foregroundGravity attribute, 183B

form layout example, 129B-130B

format strings, creating, 108B

formatNumber() method, 357B

formatting

colors, 111Bdatabase files, 669Bimages, 114B-115B

Java code, 664Bphone numbers, 357B-358Bresource references, 122Bstrings, 107Bvideo, 351B

forward compatibility, 554B

frame-by-frame animations, 116B-117B,223B-225B

animation loops, naming, 224Bgenie juggling gifts example,

223B-224Bstarting, 224Bstopping, 224B

FrameLayout views, 183B-185B

attributes, 183B-185BXML resource file example,

184B-185Bframework

applications, 27B-28BFAQ website, 449BSDK, 35B

free market for applications, 22B

functionality

applications, 97BBluetooth, 414BDDMS (Dalvik Debug Monitor

Server), 636B-637BDDMS Emulator Control tab,

642B-643Bdevice databases, 558BGLSurfaceView class, 388BGPS, 316Bmanifest files, 81B-82BOpenGL ES, 369Bpreferences, 232BRenderer class, 388BWebKit rendering engine, 308B

712B folders

Page 162: The Android Developer's Collection

Ggalleries, 194B

data-binding, 272Bimage retrieval, 273B

Gallery class, 178B

GalleryView class, 194B

GameAreaView class

defining, 511Bmethods, 511B, 513Bmulti-touch gestures, 516B-519Bsingle-touch gestures, 510B-513B

GC (Garbage Collector), 639B

gen folder, 52B

gen/com.androidbook.myfirstandroidapp/R.java file, 52B

genie juggling gifts animation example,223B-224B

Geocoder class, 319B

named locations, 320B-322Bquerying

address lines, 320Bspecific information, 320B

geocoding, 318B

AVDs with Google APIs, 319BGeoPoint objects, 324BLocation object names, retrieving,

319Bnamed locations, 320B-322Bnetwork connections, 321Bqueries

address lines, 320Bspecific information, 320B

GeomagneticField class, 412B

GeoPoint objects, 324B

GestureDetector class, 509B

interfaces, 510Bsingle-touch gesture support,

509B-510B

GestureListener interface

methods, 515Bmulti-touch implementation, 517Bsingle-touch implementation, 514B

GestureOverlayView class, 509B

gestures, 508B-509B

android.gesture package, 509Bclasses, 509Bcommand-like, 509Bmotion detection, 509Bmulti-touch, 516B-519B

ScaleGestureDetector class, 516BSimpleMultiTouchGesture applica-

tion example, 516B-519Bnatural, 518Bnavigational, 509Bsingle-touch, 509B-516B

common, 509B-510Bdetectors, 511Bfling, 515Bgame screen example, 510B-513Binterpreting, 514Bscroll, 515B

getAddressLine() method, 320B

getAll() method, 233B

getAvailableLocales() method, 544B

getBondedDevices() method, 416B

getBoolean() method, 233B

getCacheDir() method, 236B

getCenter() method, 332B

getConfiguredNetworks() method, 414B

getContentResolver() method, 268B

getDefault() method, 358B

getDefaultSensor() method, 409B

getDesiredMinimumHeight() method, 343B

getDesiredMinimumWidth() method, 343B

getDir() method, 236B

713BgetDir() method

Page 163: The Android Developer's Collection

getDisplayMessageBody() method, 361B

getDrawable() method, 116B, 343B

getExternalStoragePublicDirectory() method,548B

getFeatureName() method, 320B

getFilesDir() method, 236B

getFloat() method, 233B

getFromLocationName() method, 321B

getInt() method, 233B

getItem() method, 272B

getItemId() method, 272B

getLastNonConfigurationInstance() method,539B

getLocality() method, 320B

getLocation() method, 63B-64B

getLong() method, 233B

getMaxAddressLineIndex() method, 320B

getMaxZoom() method, 341B

getOrientation() method, 411B-412B

getResources() method, 70B

getRoaming() method, 356B

getSettings() method, 304B

getSharedPreferences() method, 70B

getString() method, 233B

getSystemService() method

ConnectivityManager, 297BNotificationManager class, 425BSensorManager class, 408BTelephonyManager class, 354BWifiManager class, 412B-413B

getTextBounds() method, 212B

getType() method, 281B-282B

getView() method, 272B

getZoom() method, 341B

getZoomRatios() method, 341B

GIF (Graphics Interchange Format), 115B

GL, initializing, 374B-375B

glColorPointer() method, 377B

glCompileShader() method, 394B

GLDebugHelper class, 373B

glDrawArrays() method, 376B

glDrawElements() method, 376B

GLES20B class, 392B

glEsVersion attribute, 368B

Global Positioning Services. See GPS

global searches, 478B

GlobalFocusChange events, 163B

GlobalLayout events, 163B

GLSurfaceView class

functionality, 388Bimplementing, 375B-390B

gluLookAt() method, 375B

gluPerspective() method, 375B

glUseProgram() method, 394B

GLUT (OpenGL Utility Toolkit), 375B

GNU

Awk (Gawk) or Nawk website, 398BGeneral Public License Version 2

(GPLv2), 20BMake 3.81 website, 398B

Google, 15B

Android Developer’s Guide, 41BAPIs Add-On, 35Bbackup service, 492Bintents, 77BMaps API key, 274B, 325B-326B,

333Bmaps integration

AVDs with Google APIs, 62B,319B

emulator location, configuring,62B-63B

locations, mapping, 322B-324BGPLv2 (GNU General Public License Version

2), 20B

714B getDisplayMessageBody() method

Page 164: The Android Developer's Collection

GPS (Global Positioning Services),315B-318B

application functionality, 316BAVD hardware option, 619Bdevice locations, finding, 316B-318Bemulator, locating, 318B, 623B-624Bsatellite classes, 333B

GPXService class, 439B

gradients (paints), 207B-208B

linear, 208Bradial, 209Bsweep, 209B

<grant-uri-permissions> tag, 95B

graphics. See images

Graphics Interchange Format (GIF), 115B

gravity attribute

LinearLayout views, 186BRelativeLayout views, 187B-189B

grids, 194B

GridView class, 194B

groups (permissions), 95B

GSM Modem AVD hardware option, 619B

HHandler class, 384B

handling events. See event handling

handsets. See devices

hardware

accessing, 407BAVD configuration options,

618B-620Bbatteries, monitoring, 417B-420BBluetooth

available, finding, 415Bclasses, 415Bconnections, 416B-417Bdevice discovery, 416B

enabling, 415B-416Bfunctionality, 414Bimplementation example,

417B-418Bpaired devices, querying, 416Bpermissions, 415Bwebsites, 421B

configuration support, 545B-546Bdevice sensors, 408B

accelerometer, 410B-411Baccessing, 408B, 409Bavailability, 409Bcalibrating, 410B-411Bdata, reading, 409B-410Bmost common, 408B-409Borientations, 411B-412BSensor Simulator, 409Btesting, 409Btrue north, finding, 412B

emulator support, 408Bfeatures, 408BWiFi

access points, scanning, 412B-413Bpermissions, 412Bsensors, 412Bsignal strength, 413Btesting, 414B

hash symbol (#), 111B

heap activity, monitoring, 639B-640B

hello-jni sample application, 399B

Hierarchy Viewer, 39B, 179B-180B

drawing issues, debugging, 180Blaunching, 179Blayout view, 180Blayouts, deconstructing, 180Bpixel perfect view, 180B-181Buser interfaces, debugging, 180B

715BHierarchy Viewer

Page 165: The Android Developer's Collection

hint attribute, 138B

history of mobile software development

applications, 17B-18Bdevice convergence, 13Bfirst generation, 9B-10Bfirst time waster games, 10BGoogle, 15Bmarket, 14BOHA (Open Handset Alliance)

formation, 16Bmanufacturers, 16Bmobile operators, 17Bwebsite, 28B

OpenGL ES, 367Bproprietary platforms, 13BWAP (Wireless Application Protocol),

11B-13Bhorizontal progress bars, 152B

horizontal scrolling, 201B

HorizontalScrollView class, 201B

hosts (App Widgets), 460B

HTTP, 288B

asynchronous processing, 291B-293Bimages, viewing, 295B-297Blatency, 298Bnetwork calls with threads,

293B-295Bnetwork status, retrieving, 297Breading Web data, 288B-289B

errors, 289Bexception handling, 288Bpermissions, 289BURL class, 288B

URL queries, 289BXML, parsing, 290B-291B

HttpURLConnection class, 289B

HVGA skin, 618B

hybrid project requirement methods, 554B

IIANA (Internet Assigned Numbers Authority),

467B

icons (applications), 87B, 599B

IDEs (integrated development environ-ments), 20B

ImageButtons, 146B

images, 114B-116B

3D. See 3D graphicsaccessing, 270B-271Badding, 115B, 269B

accessing images, 270B-271Bbinding data to Gallery control,

272Bdata retrieval, 272Bfinding content with URIs, 271Bgallery image retrieval, 273Bretrieved images, viewing,

273B-274Bandroid.graphics package, 230Banimations, 116B

android.view.animation package,226B

frame-by-frame, 116B, 117B,223B-225B

helper utilities, 116Binterpolators, 230Bloading, 227B-228Bmoving, 229B-230Brotating, 228B-229Bscaling, 229Btransparency, 228Btweening. See tweening animationstypes, 221B-223B

BitmapDrawable class, 116Bbitmaps, 212B

Bitmap class, 212Bdrawing, 213B

716B hint attribute

Page 166: The Android Developer's Collection

scaling, 213Btransforming into matrixes, 213B

buttons, 146Bcapturing with camera, 336B-340B

adding, 336B-337Bbutton click handler, 340BCamera object, instantiating,

337B-338Bcamera parameters, 338Bcamera settings, 340B-341Bcamera zoom controls, 341BCameraSurfaceView class, 337Blayouts, 339Bstarting preview, 338B-339Bstopping preview, 338BtakePicture() method, 339B

downloading from browsers, 271Bdrawing

canvases, 205B-207Bpaints, 207Bred circle on black canvas example,

205B-206Bformats, 114B-115Blive wallpapers. See live wallpapersNDK, 404Bnetwork, viewing, 295B-297BNine-Patch Stretchable

compatibility, 526B-528Bcreating, 527B-528Boverview, 115Bscaling, 527B

OpenGL ES3D graphics, 368BAPI documentation websites, 396Bcleaning up, 387Bdevice compatibility, 368B-369Bdrawing on the screen, 375B-376BEGL, initializing, 373B-374B

functionality, 369BGL, initializing, 374B-375BGLDebugHelper class, 373BGLSurfaceView class, 388Bhistory, 367Binitializing, 369B-370BKhronos OpenGL ES website,

396Bmain application thread communi-

cating with OpenGL thread,387B

OpenGL thread talking to applica-tion thread, 386B

overview, 367BRenderer class, 388BSurfaceView, creating, 370Bthread, starting, 371B-373Bversions, 368Bwebsites, 396B

OpenGL ES 2.0, 391Bconfiguring, 391Bsurface, requesting, 391B-395B

retrieved, viewing, 273B-274Bscreen captures, 645Bshapes

arcs, 219B-220Bclasses, 214Bdefining as XML resources,

214B-215Bdefining programmatically,

215B-216Bovals/circles, 219Bpaths, 220B-222Bround-corner rectangles,

217B-218Bsquares/rectangles, 216B-217Bstars, 221B-222B

sharing, 341B-342Bstoring, 101B

717Bimages

Page 167: The Android Developer's Collection

wallpaperslive wallpapers, 461B-466Bstill images, 342B-343B

Images.Media class, 260B

Images.Thumbnails class, 260B

ImageUriAdapter, 272B

IMEs (Input Method Editors), 499B

importing

database data, 673B-674BLog class, 59B

in-application searches

activities, creating, 475B-477Benabling, 470B-472Bmanifest files, 477B-478BSearch buttons, 478BSearchable Configuration documenta-

tion website, 475Bsuggestions, 472B-474Bvoice capabilities, 474B-475BXML configuration file, 471B

includeInGlobalSearch attribute, 478B

<include> tag, 124B

indicator controls. See progress bars

initializing

dialogs, 167BEGL, 373B-374BGL, 374B-375BOpenGL ES, 369B-370Bshader programs, 392B-394Bstatic Activity data, 74BText-To-Speech services, 507B

input

date retrieval, 150B-151Bfilters, 142Bgestures, 508B-509B

android.gesture package, 509Bclasses, 509Bcommand-like, 509B

motion detection, 509Bmulti-touch, 516B-519Bnatural, 518Bnavigational, 509Bsingle-touch, 509B-516B

methodsconfiguring, 90BIMEs (Input Method Editors),

499Bsoftware keyboards, 499B-502Btechnical articles website, 502B

screen orientation changes,520B-522B

textalternative resource qualifier, 535BEditText controls, 138B-142Bprediction, 502BSpinner controls, 143B-144B

time retrieval, 151Btrackballs, 519B

Input Method Editors (IMEs), 499B

InputMethodManager class, 502B

inputType attribute, 501B

insert() method

content provider data, 278B-279BSQLite database records, 242B

insertOrThrow() method, 242B

installing

App Widgets, 460B-461Bapplications, 651Bcustom binaries, 659B-660Blive folders, 485B-486Blive wallpapers, 465B-466BNDK, 398B

<integer> tag, 111B

<integer-array> tag, 111B

integer resources, 111B

718B images

Page 168: The Android Developer's Collection

integrated development environments(IDEs), 20B

Integrated Raster Imaging System GraphicsLibrary (IRIS GL), 367B

integration of applications, 21B-12B

integration points, testing, 592B-593B

Intent class, 78B

<intent-filter> tag, 92B

intents

activity transitions, 76Bcreating, 77Bexternal Activities, launching, 77BGoogle, 77Bnew activities, launching, 76B-77Borganizing with menus, 78Bpassing additional information, 78BRegistry of Intents protocols, 77B

battery monitoring, 417BBluetooth, 415B-416Bbroadcasting, 79Bfilters

configuring, 93Bcreating, 77Bprimary entry point activities,

92B-93Bregistering, 469Bremote interfaces, implementing,

446Blive folders, 481Bphone calls, making, 364Bprocessing with activities, 468Breceiving, 79Breference website, 80BSMS messages

receiving, 360Bsending, 359B

speech recognition services, 506B

interfaces

content provider, implementing, 275BContentResolver, 276BGestureDetector class, 510B

methods, 515Bmulti-touch implementation, 517Bsingle-touch implementation, 514B

OnChronometerTickListener, 156BOnDoubleTapListener, 510BOnFocusChangeListener, 164BOnGestureListener, 510BOnGlobalFocusChangeListener, 163BOnGlobalLayoutListener, 163BOnInitListener, 506BOnLongClickListener, 164BOnPreDrawListener, 163BOnTouchModeChangeListener, 162Bremote, implementing, 444B

AIDL declaration, 444Bbinder interface class name, 445Bcode implementation, 445Bconnecting/disconnecting services,

445B-446Bdisconnecting, 446Bintent filters, 446Bmultiple interfaces, 445BonBind() method, 445Bsharing across applications, 446B

SensorEventListener, 409BSharedPreferences, 232B, 233BSharedPreferences.Editor, 233B-234Buser. See user interfaces

internationalization, 539B-545B

default language, configuring,541B-543B

language alternative resources,540B-542B

719Binternationalization

Page 169: The Android Developer's Collection

device language and locale example, 541B-542B

dual language support example,540B-541B

localescustomizing, 544Bsupport, designing, 544B-545B

testing, 593BInternet access. See HTTP

Internet Assigned Numbers Authority (IANA),467B

interoperability, 566B-567B

interpolator attribute, 230B

interpolators (animations), 230B

IRIS GL (Integrated Raster Imaging SystemGraphics Library), 367B

isAfterLast() method, 246B

isDiscovering() method, 416B

isEmergencyNumber() method, 357B

isFinishing() method, 75B

isSmoothZoomSupported() method, 341B

Issue Tracker website, 32B

isZoomSupported() method, 341B

italic strings, 108B

italic text, 210B

ItemizedOverlay class, 329B-333B

iteration

mobile software development, 553Bquery results, 246B-247BWikipedia website, 570B

JJava, 21B

codeauto-complete, 664Bbuild errors, resolving, 667Bclasses, creating, 664Bformatting, 664B

imports, organizing, 664B-665Bmethods, creating, 664Bobfuscation tools, 611Brefactoring, 665B-666Breorganizing, 667B

Development Kit (JDK), 29BJavadoc-Style documentation, 667BJUnit, 35B, 581B-582Bpackages, 35BPlatform website, 41BReflection for backward compatibility,

547B-548BJavadoc-Style documentation, 667B

Java.net package, 299B

JavaScript

enabling, 304Binterface application, 308B-312B

Button control click handler, 311BJavaScript control, 311BJavaScript namespace, 309BJavaScriptExtensions class, 309BonCreate() method, 309Bsample.html file JavaScript

functions, 310B-311Bweb page, defining, 310B

tutorial website, 314BJavaScriptExtensions class, 309B

javax packages, 35B

javax.xml package, 237B

JDK (Java Development Kit), 29B

JNIEnv object, 402B

JPEG (Joint Photographic Experts Group),115B

Kkeyboards

AVD hardware option, 619Bsoftware, 499B-502B

720B internationalization

Page 170: The Android Developer's Collection

choosing, 500B-502Bcustomizing, 502B

type and availability alternativeresource qualifier, 535B

Khronos Group, 367B

Khronos OpenGL ES website, 396B

killing Activities, 75B

Llanguage support

alternative resources, 533Bdevice language and locale

example, 541B-542Bdual language example, 540B-541B

default, configuring, 541B-543Blocales

customizing, 544Bsupport, designing, 544B-545B

websites, 549Blast known location, finding, 63B-64B

launching

activities, 71B, 76B-77BADB server processes, 648Bconfigurations, creating, 46B-48B,

52B-53Bdialogs, 167Bemulator, 620B-623B, 649B-650B

running applications, 621B-623BSDK and AVD Manager, 623Bstartup options, 621B

external activities, 77Bfiles, 235BHierarchy Viewer, 179Bmonkey tool, 656Bservices, 438Bshell sessions, 649B

layout_above attribute, 189B

layout_alignBottom attribute, 188B

layout_alignLeft attribute, 188B

layout_alignParentBottom attribute, 188B

layout_alignParentLeft attribute, 188B

layout_alignParentRight attribute, 188B

layout_alignParentTop attribute, 188B

layout_alignRight attribute, 188B

layout_alignTop attribute, 188B

layout_below attribute, 189B

layout_centerHorizontal attribute, 188B

layout_centerInParent attribute, 187B

layout_centerVertical attribute, 188B

layout_column attribute, 191B

layout_gravity attribute

FrameLayout views, 184BLinearLayout views, 186B

layout_height attribute, 182B

layout_margin attribute, 182B

layout_span attribute, 191B

layout_toLeftOf attribute, 189B

layout_toRightOf attribute, 189B

layout_weight attribute, 186B

layout_width attribute, 182B

LayoutParams class, 182B

layouts, 123B-124B

alternative, 127Battributes, 181B-182Bbuilt-in, 181BButton object margin example, 183Bcontrols, 134Bcreating

programmatically, 175B-177BXML resources, 173B-175B

custom notifications, 433B-434Bdeconstructing, 180Bdesigning, 125B-127BFrameLayout, 183B-185B

attributes, 183B-185B

721Blayouts

Page 171: The Android Developer's Collection

XML resource file example,184B-185B

image capturing, 339BLinearLayout, 185B-186B

attributes, 186Bexamples, 182B, 175B-177Bhorizontal orientation, 185B

main.xml example, 123B-124Bmultiple, 192BRelativeLayout, 186B-190B

attributes, 187Bbutton controls example, 187Bviews, 189B

TableLayout, 190B-192Battributes, 191Bexample, 190BXML resource file example,

191B-192BTextView object, retrieving, 126BViewGroup subclasses, 178BWeb, designing, 302BXML, accessing, 126B

LBS (location-based services), 62B-64B,315B

AVDs with Google APIs, creating,62B

emulator location, configuring,62B-63B, 623B-624B

geocoding, 318Baddress line queries, 320BAVDs with Google APIs, 319BGeoPoint objects, 324BLocation object location names,

retrieving, 319Bnamed locations, 320B-322Bnetwork connections, 321Bspecific information queries, 320B

GPS, 315B-318Bapplication functionality, 316BAVD hardware option, 619Bdevice locations, finding,

316B-318Bemulator, locating, 318B,

623B-624Bsatellite classes, 333B

ItemizedOverlay class, 333Blast known location, finding, 63B-64Blocations, mapping

application integration, 322B-324BGoogle Maps API Key, 325B-326BURIs, 322B

mapspanning, 326B-327Bpoints of interest, marking,

327B-332Bzooming, 327B

permissions, 64BProximity Alerts, 332Bwebsite, 333B

Licensing Agreement, 32B-33B, 41B

lifecycles

activities, 72Bcallbacks, 72B-73Bdestroying Activities, 75Binitializing static activity data, 74Bkilling Activities, 75Breleasing activity data, 74Bretrieving activity data, 74Bsaving activity data, 74Bsaving state to Bundle objects, 75Bstopping activity data, 74B

dialogs, 166B-167Bservices, 438B, 449B

lighting 3D graphics, 379B-382B

linear gradients, 208B

722B layouts

Page 172: The Android Developer's Collection

LinearGradient class, 208B

linear gradients, 208B

LinearInterpolator class, 230B

LinearLayout views, 134B, 185B-186B

attributes, 186Bexample, 175B-177B, 182Bhorizontal orientation example, 185B

lines attribute, 138B

links (contextual), 136B-138B

Linux

Blog Man website, 649BOperating System, 23B-24B

lists, 194B, 197B-198B

ListView class, 178B, 194B, 197B-198B

live folders, 282B

activities, 282B, 481B-482Bcomponents, 282B-283Bcontent provider queries, 482B-484Bcreating, 481Benabling, 283Binstalling, 485B-486Blist with dates example, 285Bmanifest files, configuring, 484Boverview, 480Bpicker information, 484Bprojections, 284BURIs, defining, 283B-284Bwebsite, 487B

live server changes, managing, 569B

live wallpapers, 461B

application support, 462Bcreating, 462Bexamples, 461Binstalling, 465B-466Bmanifest file, configuring, 464B-465Bservice

creating, 462Bimplementing, 462B

service engine implementation, 463Buser events, handling, 463Bwebsite, 487BXML definition, 464B

loadAndCompileShader() method,393B-394B

loading animations, 227B-228B

locales

customizing, 544BISO 3166-1-alpha-2 Regions website,

549Bsupport, designing, 544B-545B

location-based services. See LBS

LocationListener class, 316B

LocationManager class, 316B

Log class

importing, 59Bmethods, 59B

LogCat utility, 60B, 644B

clearing logs, 654Bdates and times, 652Bfilters, 652B-653Boutput redirection, 654Bsecondary logs, accessing, 654Bviewing logs, 652B

logo, 19B

logs

clearing, 654Bdates and times, 652Bfilters, 652B-653B, 663BLogCat utility, 60B, 644Bmethods, 59Boutput redirection, 654Bsecondary, accessing, 654Bsupport, adding, 59B-60Bviewing, 652B

long click events, 164B

low memory, killing Activities, 75B

723Blow memory, killing Activities

Page 173: The Android Developer's Collection

lowest common denominator method (project requirements), 553B-554B

low-risk porting, identifying, 569B

LunarLander application, 40B

MMagic Eight Ball service, 438B

magnetic fields, 412B

maintenance designs, 565B-566B

main.xml layout example, 123B-124B

making phone calls, 362B-364B

managedQuery() method, 261B

managing

Activity transitions with intents, 76Bdevice databases, 555B-558Blive server changes, 569B

manifest files, 81B

activitiesdefining, 92Bprimary entry point, 92B-93B

App Widgets, configuring, 459Bapplication settings

descriptions, 87Bicons, 87Bnames, 87Bversioning, 86B

backup agents, registering, 495B-496Bbroadcast receivers, registering,

93B-94Bcontent providers, registering, 94Bediting, 82B

application-wide settings, 83B-84BEclipse, 82Bmanually, 84B-86Bpackage-wide settings, 82B-83Bpermissions, 83Btest instrumentation, 83B

external libraries, 92Bfunctionality, 81B-82Bintent filters, configuring, 93Blive folders, configuring, 484Blive wallpapers, configuring,

464B-465BMapView widget, 323Bmarket filtering, configuring, 599Bnames, 81Bpermissions, registering

application-defined, 95Bcontent providers, 95Brequired, 94B-95B

platform requirements, configuring,90B-92B

device features, 91Binput methods, 90Bscreen sizes, 91B-92B

searches, 477B-478Bservices, registering, 93B-94Bsettings, configuring, 96Bsystem requirements, configuring,

87B-90Bupdating, 282Bwebsite, 96B

<manifest> tag, 89B, 526B

manufacturers, 16B

device customizations, 559Bdistribution partnerships, 611B

MapActivity, 324B

MapController objects, 324B

maps, 62B-64B

AVDs with Google APIs, creating,62B

emulator location, configuring,62B-63B

ItemizedOverlay class, 333Blast known location, finding, 63B-64B

724B lowest common denominator method (project requirements)

Page 174: The Android Developer's Collection

locations, mappingapplication integration, 322B-324BGoogle Maps API Key, 325B-326BURIs, 322B

panning, 326B-327Bpoints of interest, marking,

327B-332BItemizedOverlay class, 329B-332BMapView widget, 327B-329B

Proximity Alerts, 332Bzooming, 327B

MapView widget, 323B-324B

Google Maps API Key, 325B-326Bmanifest file, 323BMapController objects, 324Bpanning, 326B-327Bpermissions, 324Bpoints of interest, marking,

327B-329BMarginLayoutParams class, 182B

markers (maps), 327B-332B

ItemizedOverlay class, 329B-332BMapView widget, 327B-329B

markets

alternatives, 610B-611BAndroid Market

country requirements, 604Bdeleting applications, 609Bdeveloper accounts, 604B-606B,

609BDistribution Agreement, 604Bhelp, 607Blicensing service, 604Bpublication, 608Brefund policy, 608B-609Bsigning-up website, 604Bupgrading applications, 609B

uploading applications, 606B-608Bwebsite, 612B

device availability, 559B-560Bfilters, 599B, 612Bfirst-to-market advantages, 23Bpackaging requirements, 599B-600Btarget, choosing, 568B

mascot, 19B

Matrix class, 213B

Max VM App Heap Size AVD hardwareoption, 620B

maxEms attribute, 136B

maximum SDK version, 90B

maxLines attribute, 136B

maxSdkVersion attribute, 88B

measureAllChildren attribute, 184B

measureText() method, 212B

media. See multimedia

MediaController widget, 345B-346B

MediaPlayer class, 60B

audio, 348B-349Bmethods, 61Bvideo, 346B

MediaRecorder class

audio, 347B-348Bvideo, 343B-345B

MediaScannerConnection class, 342B

MediaStore content provider, 259B, 260B

classes, 260Bdata requests, 260B-261B

medium-size circular progress indicators,152B

memory allocation, monitoring, 640B

menus

accessing, 120Bactivity organization, 78Bcontext menus, enabling, 159B-161B

725Bmenus

Page 175: The Android Developer's Collection

creating, 119Bintent organization, 78Boptions menus, enabling, 157B-159Bresource file example, 119Bstoring, 101BXML attributes reference, 120B

messaging (SMS)

3GPP Specifications website, 365Bandroid.telephony package, 357Bemulator messaging, 625B-628Bpermissions, 358Breceiving, 360B-362Bsending, 358B-360BWikipedia Write-Up website, 365B

<meta-data> tag, 478B

methods

addGlobalFocusChangeListener(),163B

addGlobalLayoutListener(), 163BaddOnPreDrawListener(), 163BaddOnTouchModeChangeListener(),

162BaddView(), 178BAppWidgetProvider class, 455B-456BbeginTransaction(), 244BbindService(), 438BboundCenterBottom(), 330BbroadcastIntent(), 79BcalculateAndDisplayFPS(), 385Bcancel(), 428BcancelDiscovery(), 416BcanDetectOrientation(), 521Bclose(), 250Bcompare(), 357BcreateBitmap(), 213BcreateScaledBitmap() method, 213BcreateTabContent(), 200B

dataChanged(), 496Bdelete()

contacts, 269Bcontent provider data, 280B-281B

deleteFile(), 235BdismissDialog(), 166B, 167BdivideMessage(), 362BdoInBackground(), 292BdoStartService(), 441BdrawBitmap(), 213BdrawFrame(), 404BeglDestroyContext(), 387BeglDestroySurface(), 387BeglMakeCurrent(), 387BeglTerminate(), 387BelapsedRealtime(), 156BexecSQL(), 241Bfile/directory management,

235B-236BfileList(), 236Bfilter(), 142Bfinish(), 76BforceError(), 56BformatNumber(), 357BGameAreaView class, 511B, 513BGestureListener interface, 515BgetAddressLine(), 320BgetAvailableLocales(), 544BgetBondedDevices(), 416BgetCacheDir(), 236BgetCenter(), 332BgetConfiguredNetworks(), 414BgetContentResolver(), 268BgetDefault(), 358BgetDefaultSensor(), 409BgetDesiredMinimumHeight(), 343BgetDesiredMinimumWidth(), 343B

726B menus

Page 176: The Android Developer's Collection

getDir(), 236BgetDisplayMessageBody(), 361BgetDrawable(), 116B, 343BgetExternalStoragePublicDirectory(),

548BgetFeatureName(), 320BgetFilesDir(), 236BgetFromLocationName(), 321BgetItem(), 272BgetItemId(), 272BgetLastNonConfigurationInstance(),

539BgetLocality(), 320BgetLocation(), 63B-64BgetMaxAddressLineIndex(), 320BgetMaxZoom(), 341BgetOrientation(), 411B-412BgetResources(), 70BgetRoaming(), 356BgetSettings(), 304BgetSharedPreferences(), 70BgetSystemService()

ConnectivityManager, 297BNotificationManager class, 425BSensorManager class, 408BTelephonyManager class, 354BWifiManager class, 412B-413B

getTextBounds(), 212BgetType(), 281B-282BgetView(), 272BgetZoom(), 341BgetZoomRatios(), 341BglColorPointer(), 377BglCompileShader(), 394BglDrawArrays(), 376BglDrawElements(), 376BgluLookAt(), 375B

gluPerspective(), 375BglUseProgram(), 394Binsert()

content provider data, 278B-279BSQLite database records, 242B

insertOrThrow(), 242BisAfterLast(), 246BisDiscovering(), 416BisEmergencyNumber(), 357BisFinishing(), 75BisSmoothZoomSupported(), 341BisZoomSupported(), 341BJava, creating, 664BloadAndCompileShader(), 393B-394Blogging, 59BmanagedQuery(), 261BmeasureText(), 212BMediaPlayer class, 61BmoveToFirst(), 246BmoveToNext(), 246Bnotify(), 425B-426BonAccuracyChanged(), 409BonActivityResult(), 76BonAnimateMove()

GameAreaView class, 513BGestureListener interface, 515B

onAnimateStep(), 513BonBind(), 445BonCheckedChangedListener(), 149BonClick(), 146BonConfigurationChanged(), 539BonContextItemSelected(), 161BonCreate(), 74BonCreateContextMenu(), 160BonCreateDialog(), 167BonCreateEngine(), 462BonCreateOptionsMenu(), 120B, 158B

727Bmethods

Page 177: The Android Developer's Collection

onDateChanged(), 150BonDeleted(), 456BonDestroy(), 75B, 442B-443BonDisabled(), 455BonDraw(), 205B, 511BonDrawFrame(), 390B, 404BonEnabled(), 455BonFling(), 515BonInit(), 507BonJsBeforeUnload(), 305BonKeyDown(), 386BonKeyUp(), 386BonListItemClick(), 197BonLongClick(), 164BonMove()

GameAreaView class, 513BGestureListener interface, 515B

onOptionsItemSelected(), 159BonPageFinished(), 304BonPause(), 74BonPerformSync(), 491BonPostExecute(), 292BonPreExecute(), 292BonPrepareDialog(), 167BonRatingChanged(), 155BonResetLocation()

GameAreaView class, 513BGestureListener interface, 515B

onResume(), 74BonRetainNonConfigurationInstance()

539BonSaveInstanceState(), 75BonScroll(), 515BonSensorChanged(), 409BonServiceConnected(), 445B-446BonServiceDisconnected(), 445B-446BonStart(), 440B

onStartCommand(), 440BonStop(), 62BonTouchEvent(), 509B, 511BonTouchModeChanged(), 162BonTrackballEvent(), 519BonUpdate(), 456B, 458BopenFileInput(), 235BopenFileOutput(), 235B, 236BopenOrCreateDatabase(), 240BpeekDrawable(), 343BplayMusicFromWeb(), 61Bpopulate(), 330Bpost(), 384Bpreferences, editing, 233B-234Bquery()

applications as content providers,276B-277B

SQLite databases, 246B-247BrawQuery(), 249BreadFromParcel(), 448BrecordSpeech(), 505BregisterForContextMenu(), 159BregisterListener(), 409Bremove()

preferences, 233BSQLite database records, 243B

removeDialog(), 166B, 167BrequestRestore(), 496B-497BrequestRouteToHost(), 297BsendTextMessage(), 359BsetAccuracy(), 317BsetBase(), 155BsetBuiltInZoomControls(), 304BsetColor(), 207BsetContentView(), 171BsetCurrentTabByTag(), 201BsetEGLContextClientVersion(), 392B

728B methods

Page 178: The Android Developer's Collection

setFilters(), 142BsetFlags(), 211BsetInterpolator(), 230BsetJavaScriptEnabled(), 304BsetLatestEventInfo(), 432BsetLightTouchEnabled(), 304BsetListAdapter(), 197BsetOnClickListener(), 146BsetOneShot(), 224BsetOnFocusChangeListener(), 164BsetOnLongClickListener(), 164BsetOnTimeChangedListener(), 151BsetParameters(), 340BsetShader(), 207BsetSupportZoom(), 304BsetTheme(), 170BsetTransactionSuccessful(), 244BsetVideoURI(), 346BsetWebChromeClient(), 305BsetWebViewClient(), 304BsetZoom(), 341BSharedPreferences interface, 233BshowDialog(), 166B, 167Bspeak(), 508Bstart(), 224BstartActivity(), 76B-77BstartActivityForResult(), 76BstartDiscovery(), 416BstartScan(), 413BstartService(), 438BstartSmoothZoom(), 341Bstop(), 224BstopScan(), 413BstopService(), 438BsurfaceChanged(), 336BsurfaceCreated(), 336B, 371BtakePicture(), 339B

ThrowNew(), 402BtoggleFPSDisplay(), 386BunbindService(), 446Bupdate()

applications as content providers,279B-280B

SQLite databases, 242BUri parsing, 61BwriteToParcel(), 448B

MIME types

formats, 467Breturning, 281B-282B

minEms attribute, 136B

minimum SDK versions, 89B

minLines attribute, 136B

minSdkVersion attribute, 88B

mnt/sdcard directory, 641B

mnt/sdcard/download/ directory, 641B

mobile country code alternative resourcequalifier, 533B

mobile network code alternative resourcequalifier, 533B

mobile operators, 17B

mobile software development, 17B-18B

applications, implementing, 567Barchitectures, 565Bdeployment, 568Bdevice databases

data storage, 556Bdevices, choosing, 556Bfunctionality, 558Bmanaging, 555B-557Bthird-party, 558B

device limitations, 561B, 564Bextensibility, 565B-566BGoogle, 15B

729Bmobile software development

Page 179: The Android Developer's Collection

historydevice convergence, 13Bfirst generation, 9B-10Bfirst time waster games, 10Bmarket, 14Bproprietary platforms, 13B-14BWAP (Wireless Application

Protocol), 11B-13Binteroperability, 566B-567Biteration, 553Bmaintenance, 565B-566BOHA (Open Handset Alliance)

formation, 16Bmanufacturers, 16Bmobile operators, 17Bwebsite, 28B

overview, 551Bproject documentation, 562B-563B

porting, 563Bquality assurance plans, 562B-563Bthird-party, 563B

project requirementscustomization method, 554Bhybrid approaches, 554Blowest common denominator

method, 553B-554Bquality assurance risks, 561B-562B

client-server testing, 562Bearly testing, 561Breal-world testing limitations,

561B-562Btesting on the device, 561B

source control systems, choosing,563B-564B

support requirements, 568Bdocumentation, 569Bfirmware upgrades, 569Blive server changes, 569B

low-risk porting, identifying, 569Buser crash/bug reports, 569B

target devicesacquiring, 560Bidentifying, 558B-560B

testing, 567B-568Bthird-party requirements, 555Buse cases, 555Bversioning systems, choosing, 564Bwaterfall approaches, 552Bwebsites

iterative development, 570BRapid Application Development,

570Bwaterfall development, 570BWikipedia, 570B

monkey tool

event types, weighting, 657B-658Blaunching, 656Blistening, 656B-657Bseed feature, 658Bthrottle, 658Bwebsite, 659B

Monotype font example, 210B

MotionEvent object, 509B

mouseovers (Web browsing), 304B

moveToFirst() method, 246B

moveToNext() method, 246B

moving animations, 229B-230B

MP3B playback support, adding, 61B

MultiAutoCompleteTextView class, 141B

multimedia

audio, 346BAudioManager service, 349Bfinding, 350Bformats, 351Bnotifications, 431B-432Bplaying, 348B-349B, 620B

730B mobile software development

Page 180: The Android Developer's Collection

recording, 347B-348B, 619Bringtones, 351Bsharing, 349B-350Bvoice searches, 474B-475Bwebsite, 351B

categories, 335Bfinding, 350Bformats website, 351Bhardware, 335Bimages. See imagesoptional features, configuring,

335B-336Bsupport, adding, 60B-62Bvideo, 343B

formats, 351Bplaying, 345B-346Brecording, 343B-345Bwebsite, 351B

multiple layouts, 192B

multiple screens support website, 96B

multiple themes, 170B-171B

multi-touch gestures, 516B-519B

ScaleGestureDetector class, 516BSimpleMultiTouchGesture application

example, 516B-519BMyFirstAndroidApp

AVD, creating, 51Bbuild targets, 50Bcore files/directories, 52B-51Bdebugging

emulator, 56B-59Bhandset, 65B-66B

launch configurations, creating,52B-53B

location-based services, adding,62B-64B

AVDs with Google APIs, creating,62B

emulator location, configuring,62B-63B

last known location, finding,63B-64B

logging, adding, 59B-60BMP3B playback support, adding,

60B-62Bnames, 50Bpackage name, 50Brunning in Android emulator,

53B-55B

Nnamed locations, 320B-322B

names

alternative resource directory qualifiers, 532B

animation loops, 224Bapplications, 50B, 87B, 599Bdatabase fields, 251Bmanifest files, 81Bpackages, 50Bpermissions, 95Bprojects, 50BSDKs, 19B

native applications versus third-party applications, 27B

NativeBasicsActivity.java class, 400B

natural gestures, 518B

navigation. See also LBS

alternative resource qualifiers, 535Bgestures, 509B

NDK (Native Development Kit), 397B

C/C++ advantages, 398Bcomponents, 398Bdisadvantages, 397B-398Bhello-jni sample application, 399Bimage performance, 404B

731BNDK (Native Development Kit)

Page 181: The Android Developer's Collection

installing, 398Bplatform support, 397BSimpleNDK application, 399B-400B

exception handling, 402B-403Bnative code from Java, calling,

400B-401Bparameters, handling, 401B-402Breturn values, handling, 401B-402B

websites, 405Bnetwork-driven applications, 565B

networking

asynchronous processing, 291B-293Bcalls with threads, 293B-295Bcellular networks, emulating, 298Bdiagnostics, 576B-577Bfundamentals, 287BHTTP, 288B

errors, 289Bpermissions, 289Breading data from the Web,

288B-289BURL queries, 289B

images, viewing, 295B-297Blatency, 298Bstatus, retrieving, 297BWiFi

access points, scanning, 412B-413Bpermissions, 412Bsensors, 412Bsignal strength, 413Btesting, 414B

XML, parsing, 290B-291BNexus One and Android Dev Phones website,

570B

night mode alternative resource qualifier,534B

Nine-Patch Stretchable images

compatibility, 526B-528Bcreating, 527B-528Boverview, 115Bscaling, 527B

NOAA: World Magnetic Model website, 421B

nonprimitive storage, 257B

NotePad application, 40B

NotificationManager class, 425B, 435B

notifications

audio, 431B-432Bblinking lights, 430B-431B

clearing, 431Bcolors, 430Bcustomizing, 431Bprecedence, 430Btesting, 430Burgency, 430B-431B

clearing, 428Bcomponents, 424Bcreating, 425Bcustomizing, 432B

layouts, 433B-434Btext, 432B-433B

designing, 434Bdevice support, 424Bexamples, 423Bimportance, 423BNotificationManager class, 425Breference websites, 435Bservices, 442Bstatus bar, 424B

queues, 426B-427Btext notification, creating,

425B-426Bwebsite, 435B

732B NDK (Native Development Kit)

Page 182: The Android Developer's Collection

types, 423B-424Bupdating, 427B-428Bvibration, 429B

notify() method, 425B-426B

Oobjects. See classes

OHA (Open Handset Alliance)

formation, 16Bmanufacturers, 16Bmobile operators, 17Bwebsite, 28B

onAccuracyChanged() method, 409B

onActivityResult() method, 76B

onAnimateMove() method

GameAreaView class, 513BGestureListener interface, 515B

onAnimateStep() method, 513B

onBind() method, 445B

onCheckedChangedListener() method, 149B

OnChronometerTickListener interface, 156B

onClick() method, 146B

onConfigurationChanged() method, 539B

onContextItemSelected() method, 161B

onCreate() method, 74B

onCreateContextMenu() method, 160B

onCreateDialog() method, 167B

onCreateEngine() method, 462B

onCreateOptionsMenu() method, 120B,158B

onDateChanged() method, 150B

onDeleted() method, 456B

onDestroy() method, 75B, 442B-443B

onDisabled() method, 455B

onDoubleTap gesture, 510B

onDoubleTapEvent gesture, 510B

OnDoubleTapListener interface, 510B

onDown gesture, 510B

onDraw() method, 205B, 511B

onDrawFrame() method, 390B, 404B

onEnabled() method, 455B

onFling gesture, 510B

onFling() method, 515B

OnFocusChangeListener interface, 164B

OnGestureListener interface, 510B

OnGlobalFocusChangeListener interface,163B

OnGlobalLayoutListener interface, 163B

onInit() method, 507B

OnInitListener interface, 506B

onJsBeforeUnload() method, 305B

onKeyDown() method, 386B

onKeyUp() method, 386B

onListItemClick() method, 197B

onLongClick() method, 164B

OnLongClickListener interface, 164B

onLongPress gesture, 510B

onMove() method

GameAreaView class, 513BGestureListener interface, 515B

onOptionsItemSelected() method, 159B

onPageFinished() method, 304B

onPause() method, 74B

onPerformSync() method, 491B

onPostExecute() method, 292B

OnPreDrawListener interface, 163B

onPreExecute() method, 292B

onPrepareDialog() method, 167B

OnRatingBarChangeListener class, 155B

onRatingChanged() method, 155B

onResetLocation() method

GameAreaView class, 513BGestureListener interface, 515B

onResume() method, 74B

733BonResume() method

Page 183: The Android Developer's Collection

onRetainNonConfigurationInstance()method, 539B

onSaveInstanceState() method, 75B

onScroll gesture, 510B

onScroll() method, 515B

onSensorChanged() method, 409B

onServiceConnected() method, 445B-446B

onServiceDisconnected() method,445B-446B

onShowPress gesture, 510B

onSingleTapConfirmed gesture, 510B

onSingleTapUp gesture, 510B

onStart() method, 440B

onStartCommand() method, 440B

onStop() method, 62B

onTouchEvent() method, 509B, 511B

onTouchModeChanged() method, 162B

OnTouchModeChangeListener interface,162B

onTrackballEvent() method, 519B

onUpdate() method, 456B, 458B

Open Handset Alliance (OHA). See OHA

open source licensing, 18B, 20B

openFileInput() method, 235B

openFileOutput() method, 235B, 236B

OpenGL ES

2.0, 391Bconfiguring, 391Bsurface, requesting, 391B-395B

3D graphics. See 3D graphicsAPI documentation websites, 396Bcleaning up, 387Bdevice compatibility, 368B-369Bdrawing on the screen, 375B-376BEGL, initializing, 373B-374Bfunctionality, 369BGL, initializing, 374B-375BGLDebugHelper class, 373B

GLSurfaceView classfunctionality, 388Bimplementing, 375B-390B

history, 367Binitializing, 369B-370BKhronos OpenGL ES website, 396Boverview, 367BRenderer class

functionality, 388Bimplementing, 375B-390B

SurfaceView, creating, 370Bthreads

communication, 384B-386Bstarting, 371B-373B

versions, 368Bwebsite, 396B

OpenGL Utility Toolkit (GLUT), 375B

openOrCreateDatabase() method, 240B

operating system configuration, 30B

options menus, enabling, 157B-159B

OptionsMenu control, 157B-159B

org.apache.http packages, 35B

org.json packages, 35B

org.w3c.dom package, 35B, 237B

org.xmlpull package, 35B, 237B

org.xml.sax package, 35B, 237B

orientation attribute, 186B

OrientationEventListener class, 520B

orientation (screen)

alternative resource qualifier, 534Bchanges, 520B-522Bcustomization example, 537B-538B

outsourcing testing, 596B

ovals, drawing, 219B

OvalShape object, 219B

OvershootInterpolator, 230B

734B onRetainNonConfigurationInstance() method

Page 184: The Android Developer's Collection

Ppackages

android, 35B, 131Bandroid.accounts, 489Bandroid.bluetooth, 415Bandroid.content, 232Bandroid.database.sqlite, 239Bandroid.gesture, 509Bandroid.graphics, 230Bandroid.graphics.drawable.shapes,

215Bandroid.hardware

GeomagneticField class, 412BSensorManager class, 408B

android.speech, 503Bandroid.telephony, 354B, 357Bandroid.test, 582Bandroid.view, 133Bandroid.view.animation, 226Bandroid.webkit, 307Bandroid.widget, 134Bdalvik, 35Bjava, 35Bjavax, 35Bjunit, 35Bnames, 50Borg.apache.http, 35Borg.json, 35Borg.w3c.dom, 35Borg.xmlpull, 35B, 237Borg.xml.sax, 35B, 237BXML utility, 237B

packaging applications

certification, 603Bdebugging, disabling, 600Bexporting package files, 601B-602Bicons, 599B

logging, disabling, 600Bmanifest files for market filtering,

configuring, 599Bmarket requirements, 599B-600Bnames, 599Bpermissions, 600Brelease versions, testing, 603Bsigning package files, 600B-602Btarget platforms, verifying, 599Bversions, 599B

Paint class, 207B

paints, 207B

antialiasing, 207Bcolors, choosing, 207Bgradients, 207B-208B

linear, 208Bradial, 209Bsweep, 209B

Paint class, 207Bstyles, 207Btools, 210B

panning maps, 326B-327B

Parcelable classes, implementing,446B-449B

parent views, 178B

parsing XML, 290B-291B

Path class, 220B-222B

paths (shapes), 220B-222B

peekDrawable() method, 343B

performance, testing, 594B

permission attribute, 95B

<permission> tag, 95B

permissions

ad-hoc, 25Bapplication defined, 25Baudio recording, 348Bbattery monitoring, 417B

735Bpermissions

Page 185: The Android Developer's Collection

Bluetooth, 415BContacts private data, 264B-266Bcontent providers, 95B, 262B-263Bgroups, 95Blocation-based service, 64Bmanifest files, 83BMapView widget, 324Bnames, 95Bnetworking, 289Bpackaging applications, 600Bphone calls, making, 362Bprotection levels, 95Bregistering

application-defined, 95Brequired, 94B-95B

ringtones, 351Bservices, 443BSMS messages, 358Btelephony, 354Bvibration, 429Bvideo recording, 345Bwallpapers, 343Bwebsite, 96BWebView class, 301BWiFi, 412B

persistent databases, creating, 250B

field names, 251BSQLiteOpenHelper class, extending,

251B-252Bperspectives (Eclipse), 56B, 662B

PetListAdapter, 273B

PetTracker application

binding data, 253B-244B, 254Bfield names, 251BSQLiteOpenHelper class, extending,

251B-252BPetTracker2 application, 254B-256B

PetTracker3 application, images

accessing, 270B-271Badding

binding data to Gallery control,272B

data retrieval, 272Bfinding content with URIs, 271Bgallery image retrieval, 273Bretrieved images, viewing,

273B-274Bphone calls

making, 362B-364Breceiving, 364B-365B

phone numbers

comparing, 357Bemergency, 357Bformatting, 357B-358B

PhoneGap project, 311B

platforms

alternative resource qualifiers, 536Barchitecture, 23B

Linux Operating System, 23B-24Bruntime environment, 25B

completeness, 18Bfreedoms, 18Bmarket, 14Bmascot/logo, 19Bopen source, 18B, 20Bproprietary, 13B-14Brequirements, configuring, 90B-92B

device features, 91Binput methods, 90Bscreen sizes, 91B-92B

security, 25Bapplications as operating system

users, 25Bdeveloper registration, 26B

736B permissions

Page 186: The Android Developer's Collection

permissions, 25Btrust relationships, 26B

playing

audio, 348B-349B, 620Bvideo, 345B-346B

playMusicFromWeb() method, 61B

PNG (Portable Network Graphics), 114B

points of interest, marking on maps,327B-332B

ItemizedOverlay class, 329B-332BMapView widget, 327B-329B

populate() method, 330B

Portable Network Graphics (PNG), 114B

porting

documentation, 563Blow-risk projects, identifying, 569B

post() method, 384B

PreDraw events, 163B

preferences

accessing, 231B-234Badding, 232B, 233B-234Bapplications, accessing, 70Bdata types, 231Bdeleting, 233Bfile formats, 234Bfinding, 232Bfunctionality, 232Bmethods, 233Bprivate, 232Breading, 232Bshared, 232Bupdating, 234B

PrefListenerService class, 458B

preproduction devices, testing, 590B

press-and-hold actions, 164B

primary entry point activities, 92B-93B

private data

handling, 575Bpreferences, 232B

processes

ADB server, starting/stopping, 648Bdebuggers, attaching, 638Bdevelopment, 579Breference website, 449Bstopping, 640B

programming languages, choosing, 26B

progress bars

adjusting, 153B-157Bexact values, viewing, 154Bratings, setting, 154Bthumb selectors, 153B-154Btime passage, 155B-156B

clock controls, 156B-157Bhorizontal, 152Bmedium-size circular, 152Bplacing in title bars, 153BProgressBar class, 151B-153Bstandard, 151Bvisibility, 153B

progress dialogs, 165B

ProgressBar class, 151B-153B

ProGuard website, 611B

projections (live folders), 284B

projects

adding to Eclipse workspace, 43B-44BAVDs, creating, 51Bfile locations, 50Blaunch configurations, creating,

52B-53Bnames, 50Brequirements

customization method, 554Bhybrid approaches, 554B

737Bprojects

Page 187: The Android Developer's Collection

lowest common denominatormethod, 553B-554B

prompt attribute, 144B

properties

Extras, 78BSQLite databases, configuring, 241B

proprietary platforms, 13B-14B

protection levels (permissions), 95B

<provider> tag, 94B

providers

accounts, 490BApp Widgets, 452B, 455Bcontent. See content providers

Proximity Alerts, 332B

publishing applications. See also distributingapplications

Android Market, 608Bcertification, 603Bexporting package files, 601B-602Bpackaging preparations

debugging, disabling, 600Bicons, 599Blogging, disabling, 600Bmanifest files for market filtering,

configuring, 599Bmarket requirements, 599B-600Bnames, 599Bpermissions, 600Btarget platforms, verifying, 599Bversions, 599B

release versions, testing, 603Brequirements, 598Bsigning package files, 600B-602B

putBoolean() method, 233B

putFloat() method, 233B

putInt() method, 233B

putLong() method, 234B

putString() method, 234B

Qquality assurance, 561B-562B. See also

testing

code, 580Bdiagnostics, 581Breviews, 581Bstandards, 580B-581Bunit testing, 581B-582B

documentation, 562B-563Bthird-party, 563Buser interfaces, 563B

killer apps, 594Bquery() method

applications as content providers,276B-277B

SQLite databases, 246B-247Bquerying

applications as content providers,276B-277B

Bluetooth paired devices, 416BBrowser content provider, 263B-264Bcall states, 354B-355BCallLog content provider, 262BContacts content provider,

266B-267BGeocoder class

address lines, 320Bspecific information, 320B

live folder content providers,482B-484B

MediaStore content provider,260B-261B

SQLite databases, 244Bcomplex queries, 248B-249Bcursors, 245Bfiltering results, 248Biterating results, 246B-247Bquery() method, 246B-247B

738B projects

Page 188: The Android Developer's Collection

raw queries, 249BWHERE clauses, 247B

URLs, 289BQVGA skin, 618B

Rradial gradients, 209B

RadialGradient class, 209B

radio buttons, 144B, 148B-149B

Rapid Application Development website,570B

rapid prototyping, 553B

RatingBar class, 154B-155B

raw files, 121B-122B

raw queries (SQL), 249B

rawQuery() method, 249B

readFromParcel() method, 448B

reading

device sensor data, 409B-410Bdirectory files, 236B

byte-to-byte, 237BXML, 237B

preferences, 232BWeb data, 288B-289B

errors, 289Bexception handling, 288Bpermissions, 289BURL class, 288B

<receiver> tag, 94B

receiving

intents, 79Bphone calls, 364B-365BSMS messages, 360B-362B

RecognizerIntent class, 504B-505B

recording

audio, 347B-348B, 619Bspeech, 504B-505Bvideo, 343B-345B

records (SQLite databases)

deleting, 243B-244Binserting, 242Bupdating, 242B-243B

recordSpeech() method, 505B

rectangles, drawing, 216B-217B

rectangles with rounded corners, drawing,217B-218B

RectShape object, 216B

red circle on black canvas example,205B-206B

refactoring code, 665B

Extract Local Variable tool, 666BExtract Method tool, 666B

referencing

resources, 122B-123Bsystem resources, 131B

refunding applications (Android Market),608B-609B

registerForContextMenu() method, 159B

registering

accounts, 490Bapplications as debuggable, 65Bbackup agents, 495B-496Bbackup services, 492Bbroadcast receivers, 93B-94Bcontent providers, 94Bintent filters, 469Bpermissions

application-defined, 95Brequired, 94B-95B

services, 93B-94BregisterListener() method, 409B

Registry of Intents protocols, 77B

reinstalling applications, 651B

RelativeLayout views, 186B-190B

attributes, 187Bbutton controls example, 187BXML resource file example, 189B

739BRelativeLayout views

Page 189: The Android Developer's Collection

release versions, testing, 603B

releasing activity data, 74B

remote backup services, 492B

remote interfaces, implementing, 444B

AIDL declaration, 444Bbinder interface class name, 445Bcode implementation, 445Bconnecting, 445B-446Bdisconnecting, 445B-446Bintent filters, 446Bmultiple interfaces, 445BonBind() method, 445Bsharing across applications, 446B

RemoteViews class, 456B-457B

remove() method

preferences, 233BSQLite database records, 243B

removeDialog() method, 166B, 167B

Rename tool, 665B

Renderer class

functionality, 388Bimplementing, 375B-390B

reorganizing code, 667B

requestRestore() method, 496B-497B

requestRouteToHost() method, 297B

res folder, 52B

/res/drawable-*/ directory, 98B

/res/drawable-*/icon.png folders, 52B

/res/layout/ directory, 98B

res/layout/main.xml file, 52B

resources

accessing programmatically, 103Badding, 98Baliases, 123B

alternative, 102B-103B, 531Bconfiguration changes, handling,

539Bdata retention, 539Bdefault application icon resources

example, 531Bdirectory qualifiers, 532B-537Befficiency, 538B-539Bhierarchy, 531Binternationalization, 540B-542Bperformance, 539Bprogrammatic configurations, 538Bscreen orientation customization

example, 537B-538Bwebsites, 549B

animations, 116Bandroid.view.animation package,

226Bframe-by-frame, 116B, 117B,

223B-225Bhelper utilities, 116Binterpolators, 230Bloading, 227B-228Bmoving, 229B-230Brotating, 228B-229Bscaling, 229Bstoring, 101Btransparency, 228Btweening, 116B-118B, 224B-230Btypes, 221B-223B

applications, retrieving, 70BBoolean, 110Bcolors, 111B-112B

# (hash symbol), 111Bformats, 111Bresource file example, 111B

default, 132Bdefined, 97B

740B release versions, testing

Page 190: The Android Developer's Collection

defining types with Eclipse,104B-107B

dimensions, 112B-113Bresource file example, 113Bretrieving, 113Bunit measurements, 112B

directory hierarchy, 97B-98Bdrawables, 113B-114Bimages. See imagesinteger, 111Blayout, 123B-124B

alternative, 127Battributes, 181B-182Bbuilt-in, 181BButton object margin example,

183Bcontrols, 134Bcreating programmatically,

175B-177Bcreating with XML resources,

173B-175Bcustom notifications, 433B-434Bdeconstructing, 180Bdesigning, 125B-127BFrameLayout, 183B-185Bimage capturing, 339BLinearLayout, 185B-186Bmain.xml example, 123B-124Bmultiple, 192BRelativeLayout, 186B-190BRelativeLayout views, 189BTableLayout, 190B-192BTextView object, retrieving, 126BViewGroup subclasses, 178BWeb, designing, 302BXML, accessing, 126B

menus, 119B-120Baccessing, 120Bactivity organization, 78B

context menus, enabling,159B-161B

creating, 119Bintent organization, 78Boptions menus, enabling,

157B-159Bresource file example, 119Bstoring, 101BXML attributes reference, 120B

raw files, 121B-122Breferencing, 122B-123Bselector, 116Bstoring, 97B, 101B

animations/graphics/files, 101Bstrings, 101B

strings, 107Baccessing, 108B-109Barrays, 109B-110Bbold/italic/underlining, 108Bediting, 107Bformatting, 107B, 108Bresource file example, 108Bstoring, 101B

styles, 127B-130Bapplying with a parent, 169B-170Battribute references example, 128Bform layout example, 129B-130Binheritance, 169B-170Bpadding example, 168Bpaints, 207Bpreviewing, 128Bresource ids, 130Bstoring, 128Bstyles.xml example, 128Btext size example, 168BTextView class, applying, 169B

systemandroid package, 131Breferencing, 131B

741Bresources

Page 191: The Android Developer's Collection

themes, 131B, 170B-171Bactivities, 170Bbuilt-in, 171Bentire screen, 170Bmultiple, 170B-171BsetTheme() method, 170BView objects, 170B

types, 99B-101Bwebsite, 132BXML files, 120B-121B

responsiveness, designing, 573B-574B

restore operations, 496B-497B

RestoreObserver class, 496B-497B

/res/values/ directory, 98B

res/values/strings.xml file, 52B

retrieving

Activity data, 74Bapplication resources, 70Bcontent provider data, 272BContext, 70Bdate input, 150B-151Bdimensions, 113Bdirectories, 236B

caches, 236Bfiles, 236B, 238B

gallery images, 273Bnetwork status, 297Btext input

EditText controls, 138B-142BSpinner controls, 143B-144B

TextView object, 126Btime input, 151B

revenue

ads, 612Bgeneration methods, 575B

RingtoneManager object, 351B

ringtones, 351B

risks (software development)

device limitations, 561Bquality assurance, 561B-562B

client-server testing, 562Bearly testing, 561Breal-world testing limitations,

561B-562Btesting on the device, 561B

target devicesacquiring, 560Bidentifying, 558B-560Bmanufacturer customizations, 559Bmarket availability, 559B-560B

roaming state, 356B

RotateAnimation class, 229B

rotating animations, 228B-229B

round-corner rectangles, 217B-218B

RoundRectShape object, 217B

Rubin, Andy, 16B

Run configurations, creating, 52B-53B

runtime

changes website, 549Benvironment, 25B

Ssample applications, 40B

Sans Serif font example, 210B

saving

activity data, 74BActivity state to Bundle objects, 75B

ScaleAnimation class, 229B

ScaleGestureDetector class

multi-touch gestures, 516Bnavigational gestures, 509B

scaling

animations, 229Bbitmaps, 213BNine-Patch Stretchable images, 527B

742B resources

Page 192: The Android Developer's Collection

ScanResult class, 413B

screens

aspect ratio alternative resource qualifier, 534B

compatibility. See user interfaces,compatibility

display characteristics, finding, 526Bimage captures, 645Bmultiple screen support websites,

96B, 549Borientations

alternative resource qualifiers, 534Bchanges, 520B-521B, 522Bcustomization example, 537B-538B

pixel density alternative resource qualifiers, 534B

sizesalternative resource qualifiers, 533Bconfiguring, 91B-92Bscreen aspect ratio alternative

resource qualifier, 534Bscroll gestures, 515B

scrolling, 201B

ScrollView class, 201B

SD card AVD hardware option, 620B

SDK (Software Development Kit)

accessibility framework, 502B-503Bandroid.speech package, 503Bspeech recognition services,

504B-506BText-To-Speech services,

503B, 506B-508Bandroid.view package, 133Bandroid.widget package, 134Bavailability, 20Bbuttons, 144B

basic, 144B-146Bcheck boxes, 144B, 146B-147B

radio, 144B, 148B-149Btoggles, 144B, 147B

clock controls, 156B-157Bcontext menus, enabling, 159B-161Bdata retrieval from users, 150B-151B

EditText controls, 138B-142BSpinner controls, 143B-144B

dialogs, 165Badding to activities, 166B-167Balert, 165Bcharacter picker, 165Bcustomizing, 168Bdate picker, 165Bdefining, 167BDialog class, 165Bdismissing, 167Binitializing, 167Blaunching, 167Blifecycle, 166B-167Bprogress, 165Bremoving, 167Btime picker, 166Btypes, 165B-166B

documentation, 33B-34Bdownload website, 29B, 41Bemulator, launching, 623Bframework, 35BGoogle APIs Add-On, 35BHierarchy Viewer, 179B-180B

drawing issues, debugging, 180Blaunching, 179Blayout view, 180Blayouts, deconstructing, 180Bpixel perfect view, 180B-181Buser interfaces, debugging, 180B

License Agreement, 32B-33B, 41Bnames, 19B

743BSDK (Software Development Kit)

Page 193: The Android Developer's Collection

options menus, enabling, 157B-159Bpixel perfect view, 180B-181Bprogress indicator controls

Chronometer class, 155B-156BProgressBar class, 151B-153BRatingBar class, 154B-155BSeekBar class, 153B-154B

services. See servicesstyles. See stylesthemes. See themestime input retrieval, 151Btools, 35B-36B

ADB. See ADBADT plug-in, 35B-36BAVD Manager, 36B-37BDDMS, 36B See also DDMSDraw Nine-patch, 40BEclipse Plug-In, 35Bemulator. See emulatorHierarchy Viewer. See Hierarchy

Viewertroubleshooting, 32Bupdating, 23B, 31Buser interface controls, 134B

layout, 134BTextView, 134B-138B

versions, 87B-90Bmaximum, 90Bminimum, 89Btarget, choosing, 89B

View class, 133BSearch buttons, 478B

Searchable Configuration documentationwebsite, 475B

searches, 469B-470B

global, 478B

in-application, 470B-471Bactivities, creating, 475B-477Benabling, 471B-472Bmanifest files, 477B-478BSearch buttons, 478BSearchable Configuration docu-

mentation website, 475Bsuggestions, 472B-474Bvoice capabilities, 474B-475BXML configuration file, 471B

website, 487BSearchManager class, 470B

searchSuggestAuthority attribute, 472B

searchSuggestIntentAction attribute, 472B

searchSuggestIntentData attribute, 472B

searchSuggestPath, 472B

searchSuggestSelection attribute, 472B

searchSuggestThreshold attribute, 472B

Secure Sockets Layer (SSL), 288B

security, 25B, 574B

applications as operating system users,25B

certifying applications, 603Bcopy protection, 611Bdeveloper registration, 26Bpermissions

ad-hoc, 25Bapplication defined, 25B, 95Baudio recording, 348Bbattery monitoring, 417BBluetooth, 415BCallLog content, 262B-263BContacts private data, 264B-266Bcontent providers, 95Bgroups, 95Blocation-based service, 64Bmanifest files, 83BMapView widget, 324B

744B SDK (Software Development Kit)

Page 194: The Android Developer's Collection

names, 95Bnetworking, 289Bpackaging applications, 600Bphone calls, making, 362Bprotection levels, 95Brequired, registering, 94B-95Bringtones, 351Bservices, 443BSMS, 358Btelephony, 354Bvibrations, 429Bvideo recording, 345Bwallpapers, 343Bwebsite, 96BWebView class, 301BWiFi, 412B

private datahandling, 575Btransmitting, 575B

signing package files, 600B-602Btrust relationships, 26Bwebsite, 96B

SeekBar class, 153B-154B

exact values, viewing, 154Bsimple thumb selector example,

153B-154Bselector resources, 116B

self-distribution, 609B-610B

sending SMS messages, 358B-360B

sendTextMessage() method, 359B

Sensor class, 408B

Sensor Simulator, 409B

SensorEvent class, 410B

SensorEventListener interface, 409B

SensorManager class, 408B

sensors

deviceaccelerometer, 410B-411Baccessing, 408B, 409B

availability, 409Bcalibrating, 410B-411Bdata, reading, 409B-410Bmost common, 408B-409Borientations, 411B-412BSensor Simulator, 409Btesting, 409Btrue north, finding, 412B

website, 421BWiFi, 412B

servers

ADB, starting/stopping, 648Bapplication distribution, 609B-610Btesting, 591B-592B

Service class, 439B, 449B

ServiceConnection object, implementing,445B-446B

<service> tag

broadcast receivers, registering, 94BWallpaperService class, 464B

services, 437B

Android Market licensing, 604BApp Widget update, creating,

458B-459BAudioManager, 349Bbackup, 491B

application files, 494B-495Barchived data, wiping, 655Bbackup agent implementations,

492B-493Bcontrolling with ADB, 654B-655Bforcing restores, 655Bregistering backup agents,

495B-496Bremote, choosing, 492Brequesting backups, 496Brestore operations, 496B-497Bscheduling, 655Bshared preferences files, backing up,

492B-493B

745Bservices

Page 195: The Android Developer's Collection

C2DM, 438Bcommunicating data to users

notifications, 442Btoast messages, 442B

connections, 438Bcontrolling, 443B-444Bcreating, 439B-443B

background processing, 441BdoStartService() method, 441BGPXService class implementation,

440BonStart()/onStartCommand()

methods, 440BService class, defining, 439B

criteria, 437Bexamples, 79BGPS, 315B-318B

application functionality, 316BAVD hardware option, 619Bdevice locations, finding,

316B-318Bemulator, locating, 318B,

623B-624Bsatellite classes, 333B

implementing, 438BLBS (location-based services). See

LBSlifecycle, 438B, 449Blive wallpapers, 461B

creating, 462Bimplementing, 462B

Magic Eight Ball, 438Boverview, 79BParcelable classes, implementing,

446B-449Bregistering, 93B-94Bremote interfaces, implementing, 444B

AIDL declaration, 444Bbinder interface class name, 445B

code implementation, 445Bconnecting/disconnecting,

445B-446Bdisconnecting, 446Bintent filters, 446Bmultiple interfaces, 445BonBind() method, 445Bsharing across applications, 446B

Service class website, 449BSimpleDroidWallpaper, 462Bspeech recognition, 504B-506Bstarting, 438Bstopping, 438B, 442B-443Btelephony

information, retrieving, 356Bstate, 355B-356B

testing, 591B-592BText-To-Speech, 503B, 506B-508B

converting text into sound files,508B

initializing, 507Blanguage settings, 507BOnInitListener interface, 506B

updating, 442BXML permissions file, 443B

setAccuracy() method, 317B

setBase() method, 155B

setBuiltInZoomControls() method, 304B

setColor() method, 207B

setContentView() method, 171B

setCurrentTabByTag() method, 201B

setEGLContextClientVersion() method, 392B

setFilters() method, 142B

setFlags() method, 211B

setInterpolator() method, 230B

setJavaScriptEnabled() method, 304B

setLatestEventInfo() method, 432B

setLightTouchEnabled() method, 304B

746B services

Page 196: The Android Developer's Collection

setListAdapter() method, 197B

setOnClickListener() method, 146B

setOneShot() method, 224B

setOnFocusChangeListener() method, 164B

setOnLongClickListener() method, 164B

setOnTimeChangedListener() method, 151B

setParameters() method, 340B

setShader() method, 207B

setSupportZoom() method, 304B

setTheme() method, 170B

Settings content provider, 259B, 267B

setTransactionSuccessful() method, 244B

setVideoURI() method, 346B

setWebChromeClient() method, 305B

setWebViewClient() method, 304B

setZoom() method, 341B

shader programs, initializing, 392B-394B

ShapeDrawable class, 214B

shapes

arcs, 219B-220Bclasses, 214Bdefining

programmatically, 215B-216BXML resources, 214B-215B

ovals/circles, 219Bpaths, 220B-222Bround-corner rectangles, 217B-218Bsquares/rectangles, 216B-217Bstars, 221B-222B

SharedPreferencesBackupHelper class,493B

SharedPreferences.Editor interface,233B-234B

shared preferences files, backing up,493B-494B

SharedPreferences interface, 232B, 233B

sharing

audio, 349B-350Bimages, 341B-342B

preferences, 232Bremote interfaces, 446B

shell commands, 649B-650B

backup servicesarchived data, wiping, 655Bforcing restores, 655Bscheduling, 655B

bug reports, 655B-656Bcustom binaries, installing, 659B-660Bemulator, starting/stopping,

649B-650Bissuing single, 649Blisting, 660Bmonkey tool

event types, weighting, 657B-658Blaunching, 656Blistening, 656B-657Bseed feature, 658Bthrottle, 658B

shell sessions, starting, 649BShort Message Service. See SMS messages

showDialog() method, 166B, 167B

shrinkColumns attribute, 191B

signals

loss, testing, 589Bstrength, monitoring, 356B-357B

signing package files, 600B-602B

silly mistakes, avoiding

designs, 578Bdevelopment, 583Btesting, 595B

SimpleDatabase application

file, accessing, 240BopenOrCreateDatabase() method,

240Bproperties, configuring, 241B

SimpleDataUpdateService class, 458B

747BSimpleDataUpdateService class

Page 197: The Android Developer's Collection

SimpleDroidWallpaper service, 462B

SimpleMultiTouchGesture application example, 516B-519B

SimpleNDK application

exception handling, 402B-403Bnative code from Java, calling,

400B-401Bparameters, handling, 401B-402Breturn values, handling, 401B-402B

SimpleOnGestureListener class, 510B

SimpleOrientationActivity class, 520B-521B

SimpleSearchableActivity, 475B-477B

SimpleViewDetailsActivity class, 468B

single-touch gestures, 509B-516B

common, 509B-510Bdetectors, 511Bfling, 515Bgame screen example, 510B-513Binterpreting, 514Bscroll, 515B

sizing

App Widgets, 454Bscreens

alternative resource qualifiers, 533Bconfiguring, 85B-92Bscreen aspect ratio alternative

resource qualifier, 534Btext, 136B, 212Bwallpapers, 343B

skins (AVDs), 618B

sliding drawers, 202B-203B

SlidingDrawer class, 202B-203B

SMS (Short Message Service) messages,357B

3GPP Specifications website, 365Bandroid.telephony package, 357Bemulator messaging, 625B-628Bpermissions, 358B

receiving, 360B-362Bsending, 358B-360BWikipedia Write-Up website, 365B

SmsManager class

divideMessage(), 362BgetDefault() method, 358B

Snake application, 40B

adding to Eclipse workspace, 43B-44BAVD, creating, 44B-46Blaunch configurations, creating,

46B-48Brunning in Android emulator,

47B-48Bsoftware

development. See mobile softwaredevelopment

integration, testing, 588B-589Bkeyboards, 499B-502B

choosing, 500B-502Bcustomizing, 502B

requirements, 29Bsource control systems

choosing, 563B-564BEclipse IDE integration, 661B

speak() method, 508B

speech recognition services, 504B-506B

Spinner class, 143B-144B

SQL

commands, executing, 674Bscript files, creating, 673BSQLzoo.net website, 258B

sqlite3 command-line tool, 240B, 656B,670B

ADB shell, launching, 670Bcommands, listing, 675Bdata

dumping, 672B-673Bexporting, 672Bimporting, 673B-674B

748B SimpleDroidWallpaper service

Page 198: The Android Developer's Collection

limitations, 675BSQL commands, executing, 674BSQL script files, creating, 673BSQLite databases

connecting/disconnecting,670B-671B

schemas, 672Btables

indices, 671Blisting, 671Bschemas, 672B

SQLiteDatabase class, 246B-247B

SQLite databases, 239B

binding data to user interfaces,253B-244B

adapter with ListView, 254B-256Badapters, 254B

closing, 250Bcreating, 240B

file, accessing, 240BopenOrCreateDatabase() method,

240Bproperties, configuring, 241B

datadumping, 672B-673Bexporting, 672Bimporting, 673B-674BSQL script files, creating, 673B

deleting, 250Bfile formats, 669Blimitations, 675Blisting available, 671Bmanagement classes, 239Bnonprimitive storage, 257Bpersistent, creating, 250B

field names, 251BSQLiteOpenHelper class,

extending, 251B-252B

querying, 244Bcomplex queries, 248B-249Bcursors, 245Bfiltering results, 248Biterating results, 246B-247Bquery() method, 246B-247Braw queries, 249BWHERE clauses, 247B

recordsdeleting, 243B-244Binserting, 242Bupdating, 242B-243B

schemas, 672Bsqlite3 command-line tool, 240B,

656B, 670BADB shell, launching, 670Bcommand listing, 675Bdumping data, 672B-673Bexporting data, 672Bimporting data, 673B-674Blimitations, 675BSQL commands, executing, 674BSQL script files, creating, 673BSQLite databases, connecting/

disconnecting, 670B-671BSQLite databases, schemas, 672Btables, 671B-672B

storing, 669Bstudent grade example, 675B-682B

adding data to tables, 677Bcalculated columns, 680B-682Bdeleting tables, 682Bediting, 679Bforeign keys, 678B-679Bmultiple queries, 680Bpurpose, 675B-676Bquerying, 677B-678B

749BSQLite databases

Page 199: The Android Developer's Collection

schema, 676BStudents table, 676BTests table, 676Bupdating, 679B

tablescreating, 241B-242Bdeleting, 249Bindices, 671Blisting available, 671Bschemas, 672B

transactions, 244Btriggers, 241B-242B

SQLiteOpenHelper class, 250B-252B

SQLiteQueryBuilder class, 248B-249B

SQLite website, 258B

SQLzoo.net website, 258B

squares, drawing, 216B-217B

src folder, 52B

src/com.androidbook.myfirstandroidapp/MyFirstAndroidAppActivity.java file, 52B

SSL (Secure Sockets Layer), 288B

stability, designing, 573B-574B

stand-alone applications, 565B

standard progress bars, 151B

stars, drawing, 221B-222B

start() method, 224B

startActivity() method, 76B-77B

startActivityForResult() method, 76B

startDiscovery() method, 416B

starting. See launching

startScan() method, 413B

startService() method, 438B

startSmoothZoom() method, 341B

status bar notifications, 424B

clearing, 428Bqueues, 426B-427Btext notification, creating, 425B-426B

updating, 427B-428Bwebsite, 435B

stop() method, 224B

stopping

activity data, 74BADB server processes, 648Banimations, 224Bcamera preview, 338Bemulator, 649B-650Bprocesses, 640Bservices, 438B, 442B-443Bshell sessions, 649B

stopScan() method, 413B

stopService() method, 438B

storing

databases, 669Bfiles, 235Bnonprimitive types in databases, 257Bresources, 97B, 101B

animations/graphics/files, 101Bstrings, 101B

styles, 128Bstress testing applications

eventslistening, 656B-657Btypes, weighting, 657B-658B

monkey tool, 656Brepeating events, 658Bthrottle, 658B

stretchColumns attribute, 191B

<string> tag, 107B

<string-array> tag, 109B

strings, 107B

accessing, 108B-109Barrays, 109B-110Bbold/italic/underlining, 108Bediting, 107B

750B SQLite databases

Page 200: The Android Developer's Collection

formatting, 107B, 108Bresource file example, 108Bstoring, 101B

student grades database, 675B-682B

calculated columns, 680B-682Bediting, 679Bforeign keys, 678B-679Bmultiple queries, 680Bpurpose, 675B-676Bquerying, 677B-678Bschema, 676Btables

data, adding, 677Bdeleting, 682BStudents table, 676BTests, 676B

updating, 679B<style> tag, 128B

styles, 127B-130B, 168B-170B

applying with a parent, 169B-170Battribute references example, 128Bform layout example, 129B-130Binheritance, 169B-170Bpadding example, 168Bpaints, 207Bpreviewing, 128Bresource ids, 130Bstoring, 128Bstyles.xml example, 128Btext size example, 168BTextView class, applying, 169B

support requirements, 568B

documentation, 569Bfirmware upgrades, 569Blive server changes, 569Blow-risk porting, identifying, 569Buser crash/bug reports, 569B

<supports-screen> tag, 91B, 526B

surfaceChanged() method, 336B

surfaceCreated() method, 336B, 371B

SurfaceView widget, 370B-371B

sweep gradients, 209B

SweepGradient class, 209B

switchers, 202B

Sync Adapter example application, 491B,497B

sync adapters, 491B

system

requirements, configuring, 29B,87B-90B

resourcesandroid package, 131Breferencing, 131B

TTabActivity class, 198B-200B

TabHost class, 178B

TabHost class, creating tabs, 198B

from scratch, 200B-201BTabActivity class, 198B-200B

TableLayout views, 190B-192B

attributes, 191Bexample, 190BXML resource file example,

191B-192Btables (SQLite databases)

creating, 241B-242Bdeleting, 249Bindices, 671Blisting available, 671Bschemas, 672B

tabs, creating, 198B

from scratch, 200B-201BTabActivity class, 198B-200B

751Btabs, creating

Page 201: The Android Developer's Collection

tags

<activity>, 92B<appwidget-provider>, 454B<bool>, 110B<color>, 111B<dimen>, 112B<drawable>, 114B<grant-uri-permissions>, 95B<include>, 124B<integer>, 111B<integer-array>, 111B<intent-filter>, 92B<manifest>, 89B<meta-data>, 478B<permission>, 95B<provider>, 94B<receiver>, 94B<service>

broadcast receivers, registering, 94BWallpaperService class, 464B

<string>, 107B<string-array>, 109B<style>, 128B<supports-screen>, 91B, 526B<uses-configuration>

input methods, 90Btrackballs, 519B

<uses-feature>device features, configuring, 91BGPS, 316B

<uses-permission>, 94B<uses-sdk>, 88B<wallpaper>, 464BManifest, 526B

takePicture() method, 339B

target devices

acquiring, 560Bidentifying, 558B-560B

manufacturer customizations, 559Bmarket availability, 559B-560B

targetSdkVersion attribute, 88B, 89B

telephony

call stateslistening for changes, 355Bpermissions, 354Bquerying, 354B-355Broaming, 356B

connection speeds, monitoring,356B-357B

permissions, 354Bphone calls

making, 362B-364Breceiving, 364B-365B

phone numberscomparing, 357Bemergency, 357Bformatting, 357B-358B

servicesinformation, retrieving, 356Bstate, 355B-356B

signal strength, monitoring,356B-357B

SMS messages, 357B3GPP Specifications website, 365Bandroid.telephony package, 357Bpermissions, 358Breceiving, 360B-362Bsending, 358B-360BWikipedia Write-Up website, 365B

TelephonyManager class, 354BTelephonyManager class, 354B

testing. See also quality assurance

applications, 567B-568Bautomating, 590Bbackup services, 594Bbest practices, 585B

752B tags

Page 202: The Android Developer's Collection

billing, 594Bblack box, 591Bbuild acceptance tests, 589Bclient-server, 562Bconformance, 593Bcoverage, maximizing, 589Bdefect tracking systems, 585B

defect information, logging,585B-586B

defects, defining, 586B-587Bdevelopment environment, 43B

adding projects to Eclipse workspace, 43B-44B

AVDs, creating, 44B-46Blaunch configurations, creating,

46B-48Brunning applications in Android

emulator, 47B-48Bdevices, 561B

early testing, 561Bfragmentation, 587Bsensors, 409B

emulator. See emulatorenvironments, 587Bfeasibility testing, 579B-580Binstallations, 593Bintegration points, 592B-593Binternationalization, 593Boutsourcing, 596Bperformance, 594Bpreproduction devices, 590Bpriorities, 588Bquality, 594Breal-life

device configurations, 588Blimitations, 561B-562B

reference websites, 596Brelease versions, 603Bservers, 591B-592B

services, 591B-592Bsignal loss, 589Bsilly mistakes, avoiding, 595Bsoftware integration, 588B-589Bspecialized scenarios, 592Bstarting states, 588Bstress testing applications

event listening, 656B-657Bevent types, weighting, 657B-658Bmonkey tool, launching, 656Brepeating events, 658Bthrottle, 658B

third-partyfirmware upgrades, 587Bstandards, 592B

tools, 595Bunexpected events, 594Bunit testing, 581B-582Bupgrades, 593Busability, 592Bvibration, 429Bwhite box, 591BWiFi, 414B

text

contextual links, creating, 136B-138Bdisplaying, 134B-135Bfonts

chess font, 211Bcustomizing, 211B-212Bdefault, 210BMonotype example, 210BSans Serif example, 210BsetFlags() method, 211Bsupport, 210B-211B

input methodsalternative resource qualifier, 535BIMEs (Input Method Editors),

499B

753Btext

Page 203: The Android Developer's Collection

software keyboards, 499B-502Btext prediction, 502B

input retrievalEditText controls, 138B-142BSpinner controls, 143B-144B

italic, 210Bnotifications, customizing, 432B-433Bprediction, 502Bsizing, 136B, 212Bstatus bar notification, creating,

425B-426Btext attribute, 135B

textOn/textOff attributes, 147B

Text-To-Speech services, 503B, 506B-508B

converting text into sound files, 508Binitializing, 507Blanguage settings, 507BOnInitListener interface, 506B

texturing 3D graphics, 381B-384B

TextView class, 134B-138B

contextual links, creating, 136B-138Bheight, 136Bretrieving, 126Bstyles, applying, 169Btext attribute, 135Bwidth, 136B

themes, 131B, 170B-171B

applyingactivities, 170Bentire screen, 170BView objects, 170B

built-in, 171Bmultiple, 170B-171BsetTheme() method, 170B

third-party

applications versus native applications,27B

design standards, 576B

device databases, 558Bdocumentation, 563Bfirmware considerations, 587Bsoftware development requirements,

555Btesting standards, 592B

threads

applicationactivity, monitoring, 638B-639Bviewing, 637B-638B

OpenGLstarting, 371B-373Btalking to application thread,

384B-385Breference website, 449B

ThrowNew() method, 402B

time

input retrieval, 151Bpassage progress bars, 155B-156Bpicker dialogs, 166B

TimePicker class, 151B

Toast messages, 146B, 442B

toggle buttons, 144B

toggleFPSDisplay() method, 386B

toggles, 147B

tools, 35B-36B

ADB. See ADBADT plug-in, 35B-36Banimation helper, 116BAsset Packaging, 98BAVD Manager, 36B-37Bcode obfuscation, 611BDDMS. See DDMSdesign, 578Bdevelopment, 583BDraw Nine-patch, 40B, 527B-528BEclipse Plug-In, 35Bemulator. See emulator

754B text

Page 204: The Android Developer's Collection

Exerciser Monkey, 594B, 596BExtract Local Variable, 666BExtract Method, 666BGLUT (OpenGL Utility Toolkit),

375BHierarchy Viewer, 39B, 179B-180B

drawing issues, debugging, 180Blaunching, 179Blayout view, 180Blayouts, deconstructing, 180Bpixel perfect view, 180B-181Buser interfaces, debugging, 180B

LogCat, 60B, 644Bclearing logs, 654Bdates and times, 652Bfilters, 652B-653Boutput redirection, 654Bsecondary logs, accessing, 654Bviewing logs, 652B

monkeyevent types, weighting, 657B-658Blaunching, 656Blistening, 656B-657Bseed feature, 658Bthrottle, 658Bwebsite, 659B

paints, 210BRename, 665Bsqlite3, 240B, 670B, 656B

ADB shell, launching, 670Bcommand listing, 675Bdatabase connections, 670B-671Bdatabase schemas, 672Bdumping data, 672B-673Bexporting data, 672Bimporting data, 673B-674Blimitations, 675B

listing available databases, 671BSQL commands, executing, 674BSQL script files, creating, 673Btable indices, 671Btable schemas, 672Btables, listing, 671B

testing, 595BXML packages, 237B

touch gestures. See gestures

touch screen

alternative resource qualifier, 535BAVD hardware option, 619Bmode changes, 161B-162B

trackballs, 519B, 619B

transactions (SQL), 244B

transformations (tweened animations)

alpha transparency, 228Bdefining, 224Binterpolators, 230Bmoving, 229B-230Brotating, 228B-229Bscaling, 229B

transitions (activities), 76B

external Activities, launching, 77Bintent action/data types, 77Bnew activities, launching, 76B-77Bpassing additional information, 78B

TranslateAnimation class, 230B

transmitting private data, 575B

transparency (animations), 228B

triangles, drawing, 375B-376B

triggers (SQL), 241B-242B

troubleshooting

backup services, 497Bbuild errors, 667Bdevice specific bugs, 582BSDK, 32B

755Btroubleshooting

Page 205: The Android Developer's Collection

signal loss, 589Bsupport requirements, 568B

documentation, 569Bfirmware upgrades, 569Blive server changes, 569Blow-risk porting, identifying, 569Buser crash/bug reports, 569B

true north, finding, 412B

trust relationships, 26B

tweening animations,116B, 117B-118B, 224B-230B

definingprogrammatically, 226BXML resources, 226B

loading, 227B-228Bsimultaneously/sequentially,

226B-227Btransformations

alpha transparency, 228Bdefining, 224Binterpolators, 230Bmoving, 229B-230Brotating, 228B-229Bscaling, 229B

TYPE_ACCELEROMETER sensor, 408B

TYPE_GYROSCOPE sensor, 408B

TYPE_LIGHT sensor, 409B

TYPE_MAGNETIC_FIELD sensor, 409B

TYPE_ORIENTATION sensor, 408B

TYPE_PRESSURE sensor, 409B

TYPE_PROXIMITY sensor, 409B

TYPE_TEMPERATURE sensor, 409B

UunbindService() method, 446B

underlining strings, 108B

unexpected events, testing, 594B

Uniform Resource Identifiers. See URIs

uninstalling applications, 651B

update() method

applications as content providers,279B-280B

SQLite databases, 242Bupdating

Android Market applications, 609BApp Widgets, 453B, 454B

onUpdate() method, 458Bupdate service, creating,

458B-459Bapplications as content providers,

279B-280Bbest practices, 577B-578Bcontent provider data, 268B-269Bfirmware upgrades, 569Bmanifest files, 282Bnotifications, 427B-428Bpreferences, 234BSDK, 23B, 31Bservices, 442BSQLite database records, 242B-243Btesting, 593B

uploading applications to Android Market,606B-608B

Uri class, 61B

UriMatcher class, 277B-278B

URIs (Uniform Resource Identifiers), 25B

content, finding, 271Bdefining, 276BLiveFolders, defining, 283B-284Blocations, mapping, 322Bpattern matching, 277B-278B

URL class, 288B

URLs, querying, 289B

URLUtil class, 307B

usability testing, 592B

USB drivers for Windows website, 67B

756B troubleshooting

Page 206: The Android Developer's Collection

use cases, developing, 555B

UserDictionary content provider, 259B, 267B

user event handling. See event handling

user interfaces, 134B

adapters, 194Barrays, 194B-195Bbinding data, 196Bcursor, 195B-196Bevent handling, 197B

buttons, 144Bbasic, 144B-146Bcheck boxes, 144B, 146B-147Bradio, 144B, 148B-149Btoggles, 144B, 147B

clocks, 156B-157Bcompatibility

Nine-Patch Stretchable images,526B-528B

screen support, 526Bworking square principle,

528B-531Bcontext menus, enabling, 159B-161Bdatabase data, binding, 253B-244B

adapter with ListView, 254B-256Badapters, 254B

date input retrieval, 150B-151Bdebugging, 180Bdesigning, 572B-573Bdialogs, 165B

adding to activities, 166B-167Balert, 165Bcharacter picker, 165Bcustomizing, 168Bdate picker, 165Bdefining, 167BDialog class, 165Bdismissing, 167B

initializing, 167Blaunching, 167Blifecycle, 166B-167Bprogress, 165Bremoving, 167Btime picker, 166Btypes, 165B-166B

documentation, 563Bgalleries, 194Bgrids, 194Blayouts, creating, 134B

programmatically, 175B-177BXML resources, 173B-175B

lists, 194B, 197B-198Boptions menus, enabling, 157B-159Bprogress indicators

Chronometer class, 155B-156BProgressBar class, 151B-153BRatingBar class, 154B-155BSeekBar class, 153B-154B

scrolling support, 201Bsliding drawers, 202B-203Bstyles. See stylesswitchers, 202Btabs, 198B

creating from scratch, 200B-201BTabActivity class implementation,

198B-200Btext input retrieval

EditText controls, 138B-142BSpinner controls, 143B-144B

TextView, 134B-138Bcontextual links, creating,

136B-138Bheight, 136Btext attribute, 135Bwidth, 136B

757Buser interfaces

Page 207: The Android Developer's Collection

themes. See themestime input retrieval, 151Bview containers, 193BViewGroups, 178B

child View objects, adding, 178Blayout classes, 178Bsubclass categories, 178BView container controls, 178B

users

applications as operating system users,25B

billing, 611B-612Bgeneration methods, 575Btesting, 594B

crash/bug reports, 569B, 655B-656Bdemands, meeting, 572Binput retrieval

EditText controls, 138B-142BSpinner controls, 143B-144B

<uses-configuration> tag

input methods, 90Btrackballs, 519B

<uses-feature> tag

device features, configuring, 91BGPS, 316B

<uses-permission> tag, 94B

<uses-sdk> tag, 88B

utilities. See tools

Vversions

applications, 86B, 599Bcompatibility, 546B-548B

API levels, finding, 546B-547Bbackward compatibility with Java Reflection,

547B-548B

OpenGL ES, 368B

SDK, 87B-90Bmaximum, 90Bminimum, 89Btarget, choosing, 89B

versioning systems, choosing, 564Bvertical scrolling, 201B

vertices (3D graphics)

coloring, 377B-378Bdrawing, 376B-377B

vibration notifications, 429B

video, 343B

formats, 351Bplaying, 345B-346Brecording, 343B-345Bwebsite, 351B

Video.Media class, 260B

VideoView widget, 345B-346B

View class, 133B

attributes, 127Bbinding data. See adapterscontainers

adapters, 194B-197Bbuilt-in, 193Bgalleries, 194Bgrids, 194Blists, 194B, 197B-198Bscrolling support, 201Bsliding drawers, 202B-203Bswitchers, 202Btabs. See tabs

drawing issues, debugging, 180Bgalleries, 178BHierarchy Viewer, 179B-180B

drawing issues, debugging, 180Blaunching, 179Blayout view, 180B

758B user interfaces

Page 208: The Android Developer's Collection

pixel perfect view, 180B-181Buser interfaces, debugging, 180B

list views, 178BOnFocusChangeListener interface,

164BOnLongClickListener interface, 164Bparent-child relationships, 178Btab hosts, 178Bthemes, applying, 170BViewWithRedDot subclass,

205B-206BViewGroups class, 178B

attributes, 182Bchild View objects, adding, 178Bsubclasses

categories, 178Blayout classes, 178BView container controls, 178B

viewing

application threads, 637B-638Blive folder picker information, 484Blogs, 652Bnetwork images, 295B-297Bprogress bars, 153Bretrieved images, 273B-274Bstyles, 128Btext, 134B-135BWeb content, 302B-304B

ViewSwitcher class, 202B

ViewTreeObserver class

OnGlobalFocusChangeListener interface, 163B

OnGlobalLayoutListener, 163BOnPreDrawListener interface, 163BOnTouchModeChangeListener

interface, 162BViewWithRedDot class, 205B-206B

voice searches, 474B-475B

WW3School’s JavaScript Tutorial website,

314B

WallpaperManager class, 342B

wallpapers

live, 461Bapplication support, 462Bcreating, 462Bimplementing services, 462Binstalling, 465B-466Bmanifest file, configuring,

464B-465Bservice engine implementation,

463Buser events, handling, 463BXML definition, 464B

still images, 342B-343BWallpaperService class, 462B

<wallpaper> tag, 464B

WAP (Wireless Application Protocol),11B-13B

waterfall development, 552B, 570B

Web

browsing, 301B-302Bchrome, adding, 305B-307Bevent handling, 304B-305BFlash support, 311B-313BJavaScript, enabling, 304Bmouseovers, 304Bsettings, configuring, 304Bzooming, 304B

content, loading, 302B-304Bdata, reading, 288B-289B

errors, 289Bexception handling, 288Bpermissions, 289BURL class, 288B

759BWeb

Page 209: The Android Developer's Collection

layouts, designing, 302BWebKit rendering engine, 301B

android.webkit package, 307Bclasses, 307Bfunctionality, 308BJavaScript interface application,

308B-312BOpen Source Project website, 314Bsupport, 307B

WebBackForwardList class, 307B

WebChromeClient class, 305B-307B

WebHistoryItem class, 307B

WebKit rendering engine, 301B

android.webkit package, 307Bclasses, 307Bfunctionality, 308BJavaScript interface application,

308B-312BButton control click handler, 311BJavaScript control, 311BJavaScript namespace, 309BJavaScriptExtensions class, 309BonCreate() method, 309Bsample.html file JavaScript func-

tions, 310B-311Bweb page, defining, 310B

Open Source Project website, 314Bsupport, 307B

WebSettings class, 304B

websites

3GPP Specifications, 365BActivity class, 80BADB, 39BAdobe AIR for Android

beta program, 313BTool Suite, 314B

alternative resources, 549B

AndroidDev Guide:“Developing on a

Device” website, 67BDevelopment, 28B, 398B, 574Bsign-up, 604B

Android Market, 612Bcountry requirements, 604BDeveloper Distribution Agreement,

604Bhelp, 607Blicensing service, 604B

Android.net package, 299BAPI levels, 96BApiDemos application, 40BApp Widgets, 454B, 487Bash shell, 649Baudio, 351Bbackup services, 497Bbackward compatibility without

reflection, 548Bbest practices, 584BBluetooth, 421BBorland SilkTest, 589Bbug resolution process, 32BBusyBox, 660BC2DM (Cloud to Device Messaging),

438Bchess font, 211Bcloud computing Wikipedia, 497Bcompatibility, 549BContactsContract content provider,

264Bcontent providers, 285BContext class reference, 80BCygwin, 398BDDMS, 38BEclipse, 41B

download, 29BIDE, 30B

760B Web

Page 210: The Android Developer's Collection

emulator, 38BExerciser Monkey command-line

tool, 596Bextreme programming, 570Bframework FAQ, 449BGNU

Awk (Gawk) or Nawk, 398BMake 3.81, 398B

GoogleAndroid Developer’s Guide, 41BAPIs Add-On, 35Bbackup service, 492Bintents, 77BMaps API key, 274B, 333B

IANA (Internet Assigned NumbersAuthority), 467B

input methods, 502BinputType attribute, 501Bintent reference, 80BISO 3166-1-alpha-2 Regions, 549BIssue Tracker, 32BJava

JDK (Java Development Kit), 29BJUnit, 582BPlatform, 41B, 548B

Java.net package, 299BKhronos OpenGL ES, 396Blanguage support, 549BLicensing Agreement, 41BLinux Blog Man, 649Blive folders, 487Blive wallpapers, 487Blocations and maps, 333BLunarLander application, 40BManifest tag, 526Bmanifest files, 96Bmarket filters, 599B, 612B

memory allocation, monitoring, 640Bmonkey tool, 659Bmultimedia formats, 351Bmultiple screen support, 96B, 549BNDK, 405BNexus One and Android Dev Phones,

570BNOAA:World Magnetic Model, 421BNotePad application, 40BNotificationManager class, 435Bnotifications, 435BOpen Handset Alliance (OHA), 28BOpenGL ES, 396BOpenGL ES API documentation,

396BPhoneGap project, 311Bprocesses and threads, 449BProGuard, 611BRegistry of Intents protocols, 77Bresources, 132Bruntime changes, 549Bscreen orientation changes, 522BSDK

documentation, 33B-34Bdownload, 29B, 41Bupdates, 31B

Searchable Configuration documenta-tion, 475B

searches, 487Bsecurity and permissions, 96BSensor Simulator, 409Bsensors, 421Bservices

lifecycle, 449BService class, 449B

Snake application, 40BSQLite, 258BSQLzoo.net, 258B

761Bwebsites

Page 211: The Android Developer's Collection

Sync Adapter example application,491B, 497B

system requirements, 29Btesting references, 596Bunit testing tutorial, 582BUSB drivers for Windows, 67Bvideo, 351BW3School’s JavaScript Tutorial, 314BWebKit

Open Source Project, 314Brendering engine, 301B

Wikipediaiterative development, 570BRapid Application Development,

570Bsoftware process, 570Bsoftware testing, 596Bwaterfall development, 570BWrite-Up, 365B

Windows USB driver, 30BXML

attributes for menus reference,120B

Pull Parsing, 299BWebView class. See also WebKit rendering

engine

benefits, 307Bchrome, adding, 305B-307Bcontent, loading, 302B-304Bevent handling, 304B-305Blayouts, designing, 302Bsettings, configuring, 304BWeb browsing, 301B-302B

WebViewClient class, 304B-305B

WHERE clauses (SQL queries), 247B

white box testing, 591B

widgets

MapView, 323B-324BGoogle Maps API Key, 325B-326Bmanifest file, 323BMapController objects, 324Bpanning, 326B-327Bpermissions, 324Bpoints of interest, marking,

327B-329BMediaController, 345B-346BSurfaceView, 370B-371BVideoView, 345B-346B

WiFi

access points, scanning, 412B-413Bpermissions, 412Bsensors, 412Bsignal strength, 413Btesting, 414B

WifiManager class, 412B-413B

Wikipedia websites

iterative development, 570BRapid Application Development,

570Bsoftware

processes, 570Btesting, 596B

waterfall development, 570BWrite-Up, 365B

windows (Eclipse IDE)

maximizing, 662Bminimizing, 662Bmultiple file sections, viewing, 662Bopen, limiting, 663Bside by side view, 662B

Windows USB drivers, 30B, 67B

Wireless Application Protocol (WAP),11B-13B

762B websites

Page 212: The Android Developer's Collection

WML (Wireless Markup Language), 12B

working square principle, 528B-531B

World Magnetic Model, 412B

WQVGA400B skin, 618B

WQVGA432B skin, 618B

writeToParcel() method, 448B

WVGA800B skin, 618B

WVGA854B skin, 618B

XXML (Extensible Markup Language)

App Widget definitions, 453B-454Battributes, 120Bin-application search files, 471Blayouts

accessing, 120B-121B, 126Bcreating, 173B-175B

live wallpaper definition, 464Bmanifest files. See manifest filesparsing, 290B-291BPull Parsing website, 299Bservices permissions file, 443Bshapes, defining, 214B-215BSMS permissions, 358Btags. See tagstelephony state information, 354Btweened animations, defining, 226Butility packages, 237B

Zzooming

cameras, 341Bmaps, 327BWeb browsing, 304B

763Bzooming