Android Wireless Application Development

Transcription

Android WirelessApplicationDevelopmentVolume II: Advanced TopicsThird Edition

This page intentionally left blank

Android WirelessApplicationDevelopmentVolume II: Advanced TopicsThird EditionLauren DarceyShane ConderUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCape Town Sydney Tokyo Singapore Mexico City

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and thepublisher was aware of a trademark claim, the designations have been printed with initialcapital letters or in all capitals.Editor-in-ChiefMark TaubThe 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.DevelopmentEditorSonglin QiuThe 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) 382-3419corpsales@pearsontechgroup.comFor sales outside the United States, please contact:International Salesinternational@pearsoned.comVisit us on the Web: informit.com/awLibrary of Congress Cataloging-in-Publication Data is on file.Copyright 2012 Lauren Darcey and Shane ConderAll 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 prohibitedreproduction, storage in a retrieval system, or transmission in any form or by any means,electronic, mechanical, photocopying, recording, or likewise. To obtain permission to usematerial from this work, please submit a written request to Pearson Education, Inc.,Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or youmay fax your request to (201) 236-3290.Android is a 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 anddevelopment 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 /).ISBN-13: 978-0-321-81384-8ISBN-10: 0-321-81384-7Text printed in the United States on recycled paper at R.R. Donnelley in Crawfordsville,Indiana.First printing, July 2012Acquisitions EditorLaura LewinManaging EditorKristy HartProject EditorBetsy HarrisCopy EditorDeadline-DrivenPublishingIndexerLisa StumpfProofreaderPaula LowellTechnicalReviewersTony HillersonDouglas JonesRay RischpaterPublishingCoordinatorOlivia BasegioMultimediaDeveloperDan ScherfBook DesignerGary AdairSenior CompositorGloria Schurick

This book is dedicated to ESC.

This page intentionally left blank

ContentsIntroduction1I: Advanced Android Application Design Principles1 Threading and Asynchronous ProcessingThe Importance of Processing AsynchronouslyWorking with the AsyncTask Class10Working with the Thread Class13Working with Loaders14Understanding StrictMode14Summary915References and More Information2 Working with Services1517Determining When to Use Services17Understanding the Service Lifecycle18Creating a Service18Controlling a Service23Implementing a Remote Interface24Implementing a Parcelable Class26Using the IntentService Class29Summary933References and More Information333 Leveraging SQLite Application DatabasesStoring Structured Data Using SQLiteDatabases 35Creating a SQLite Database36Creating, Updating, and DeletingDatabase Records38Working with Transactions4035

viiiContentsQuerying SQLite Databases41Closing and Deleting a SQLiteDatabase46Designing Persistent Databases47Binding Data to the ApplicationUser Interface50Summary55References and More Information554 Building Android Content Providers 57Acting as a Content Provider 57Implementing a Content ProviderInterface58Defining the Data URI59Defining Data Columns59Implementing Important Content ProviderMethods59Updating the Manifest File65Enhancing Applications Using ContentProviders 65Accessing Images on the DeviceSummary6671References and More Information715 Broadcasting and ReceivingIntents73Sending Broadcasts 73Sending Basic Broadcasts 74Sending Ordered BroadcastsReceiving Broadcasts7475Registering to Receive Broadcasts 76Handling Incoming Broadcasts fromthe System77Securing Application BroadcastsSummary8080References and More Information81

Contents6 Working with Notifications 83Notifying the User83A Word on Compatibility84Notifying with the Status Bar 84Using the NotificationManager Service85Creating a Simple Text Notification withan Icon 85Working with the Notification QueueUpdating Notifications88Clearing Notifications9086Vibrating the Phone 91Blinking the Lights92Making Noise93Customizing the Notification94Designing Useful NotificationsSummary9697References and More Information97II: Advanced Android User Interface Design Principles7 Designing Powerful User Interfaces 99Following Android User Interface GuidelinesWorking with MenusUsing Options Menus100Using Context Menus103Using Popup MenusEnabling Action Bars99100105105Building Basic Action Bars 106Customizing Your Action Bar110Handling Application Icon Clicks on theAction Bar112Working with Screens That Do Not RequireAction Bars114Introducing Contextual Action Mode114Using Advanced Action Bar Features114ix

xContentsWorking with Styles 114Building Simple Styles115Leveraging Style InheritanceWorking with ThemesSummary117119121References and More Information8 Handling Advanced User InputWorking with Textual Input MethodsWorking with Software Keyboards122123123123Working with Text Prediction and UserDictionaries126Using the Clipboard FrameworkHandling User Events126127Listening for Touch Mode Changes 127Listening for Events on the Entire ScreenListening for Long Clicks129Listening for Focus ChangesWorking with Gestures128130131Detecting User Motions Within a View131Handling Common Single-Touch Gestures132Handling Common Multi-Touch Gestures139Making Gestures Look Natural142Using the Drag and Drop FrameworkWorking with the Trackball143143Handling Screen Orientation Changes 144Summary146References and More Information1479 Designing Accessible Applications 149Exploring the Accessibility Framework 149Leveraging Speech Recognition ServicesLeveraging Text-To-Speech ServicesSummary155158References and More Information158151

Contents10 Best Practices for Tablet and Google TVDevelopment159Understanding Device Diversity159Don’t Make Assumptions about DeviceCharacteristics 159Designing Flexible User Interfaces160Attracting New Types of Users161Leveraging Alternative Resources161Using Screen Space Effectively on BigLandscape Screens161Developing Applications for Tablets162Developing Applications for Google TV 164Optimizing Web Applications for Google TV165Developing Native Android Applications forGoogle TV165Developing Apps for the Amazon Kindle FireSummary166167References and More Information168III: Leveraging Common Android APIs11 Using Android Networking APIs169Understanding Mobile NetworkingFundamentals169Understanding Strict Mode with NetworkingAccessing the Internet (HTTP)170170Reading Data from the Web170Using HttpURLConnection 171Parsing XML from the Network172Handling Network OperationsAsynchronously 174Retrieving Android Network StatusSummary179181References and More Information12 Using Android Web APIs181183Browsing the Web with WebView183Designing a Layout with a WebView Control184Loading Content into a WebView Control184xi

xiiContentsAdding Features to the WebView Control186Managing WebView State 189Building Web Extensions Using WebKit190Browsing the WebKit APIs 190Extending Web Application Functionality toAndroid 190Working with Flash195Enabling Flash Applications195Building AIR Applications for AndroidSummary196196References and More Information19613 Using Location-Based Services APIs197Using Global Positioning Services (GPS)197Using GPS Features in Your Applications198Determining the Location of the Device198Locating Your EmulatorGeocoding LocationsMapping Locations200200204Mapping Intents 205Mapping Views206Getting Your Debug API Key207Panning the Map View209Zooming the Map View210Marking the Spot211Doing More with Location-Based ServicesSummary216217References and More Information14 Using Android Multimedia APIsWorking with Multimedia219Working with the Camera220217219Capturing Still Images Using the CameraWorking with Video229Working with Face Detection233220

ContentsWorking with Audio233Recording Audio 233Playing Audio235Sharing Audio236Searching for Multimedia236Working with Ringtones238Summary238References and More Information15 Using Android Telephony APIsWorking with Telephony Utilities238239239Gaining Permission to Access Phone StateInformation240Requesting Call State240Requesting Service Information242Monitoring Signal Strength and Data ConnectionSpeed 243Working with Phone Numbers243Using SMS 244Gaining Permission to Send and Receive SMSMessages244Sending an SMS245Receiving an SMS247Making and Receiving Phone CallsMaking Phone Calls249Receiving Phone Calls251Working with SIPSummary248251251References and More Information25216 Accessing Android’s Hardware SensorsInteracting with Device HardwareUsing the Device Sensors253254Working with Different Sensors254Configuring the Android Manifest File forSensors255Acquiring a Reference to a Sensor 256Reading Sensor Data256253xiii

xivContentsCalibrating Sensors258Determining Device OrientationFinding True NorthMonitoring the BatterySummary258258258261References and More Information26117 Using Android’s Optional Hardware APIsWorking with Bluetooth263263Checking for the Existence of BluetoothHardware264Enabling Bluetooth264Querying for Paired DevicesDiscovering Devices265265Establishing Connections Between DevicesWorking with USB266267Working with USB AccessoriesWorking as a USB HostWorking with Android Beam268269269Enabling Android Beam Sending270Receiving Android Beam Messages 271Configuring the Manifest File for AndroidBeam 272Working with Wi-Fi273Introducing Wi-Fi Direct273Monitoring Wi-Fi State274Summary276References and More Information276IV: Drawing, Animations, and Graphics Programmingwith Android18 Developing Android 2D GraphicsApplications279Drawing on the Screen279Working with Canvases and Paints 279

ContentsWorking with Text284Using Default Fonts and Typefaces 284Using Custom Typefaces285Measuring Text Screen RequirementsWorking with BitmapsDrawing Bitmap Graphics on a CanvasScaling Bitmap Graphics287287Transforming Bitmaps Using MatrixesWorking with Shapes287287287289Defining Shape Drawables as XMLResources289Defining Shape Drawables Programmatically 290Drawing Different Shapes 291Leveraging Hardware Acceleration FeaturesControlling Hardware Acceleration298Fine-Tuning Hardware Acceleration298Summary297299References and More Information19 Working with Animation299301Exploring Android’s Animation Abilities 301Working with Frame-by-Frame AnimationWorking with Tweened Animations304Working with Property Animation309Working with Different Interpolators313Summary302314References and More Information31420 Developing Android 3D GraphicsApplications315Working with OpenGL ES315Leveraging OpenGL ES in Android316Ensuring Device Compatibility316Using OpenGL ES APIs in the Android SDKHandling OpenGL ES Tasks ManuallyCreating a SurfaceViewStarting Your OpenGL ES ThreadInitializing EGL321318318319317xv

xviContentsInitializing GL323Drawing on the Screen323Drawing 3D Objects 325Drawing Your Vertices325Coloring Your Vertices326Drawing More Complex ObjectsLighting Your Scene329Texturing Your Objects331327Interacting with Android Views and Events333Enabling the OpenGL Thread to Talk to theApplication Thread333Enabling the Application Thread to Talk to theOpenGL Thread 335Cleaning Up OpenGL ES337Using GLSurfaceView (Easy OpenGL ES)Using OpenGL ES 2.0337341Configuring Your Application forOpenGL ES 2.0 341Requesting an OpenGL ES 2.0 SurfaceWorking with RenderScript341345Defining RenderScript Functionality 346Rendering to a Custom View ControlSummary350353References and More Information21 Using the Android NDK353355Determining When to Use the Android NDKInstalling the Android NDK356Exploring the Android NDK357355Running an Android NDK Sample Application 357Creating Your Own NDK ProjectCalling Native Code from Java357358Handling Parameters and Return ValuesUsing Exceptions with Native Code 360Using Native Activities362Improving Graphics Performance362A Comparison to RenderScript363Summary363References and More Information364359

ContentsV: Maximizing Android’s Unique Features22 Extending Android Application ReachEnhancing Your Applications365Working with App Widgets366Creating an App Widget367Installing an App Widget374Becoming an App Widget Host365375Working with Live Wallpapers 375Creating a Live Wallpaper376Creating a Live Wallpaper Service376Creating a Live Wallpaper Configuration378Configuring the Android Manifest File forLive Wallpapers 379Installing a Live Wallpaper379Acting as a Content Type Handler381Determining Intent Actions and MIME Types382Implementing the Activity to Processthe Intents383Registering the Intent FilterSummary384384References and More Information23 Enabling Application Search384385Making Application Content Searchable385En

Developing Native Android Applications for Google TV 165 Developing Apps for the Amazon Kindle Fire 166 Summary 167 References and More Information 168 III: Leveraging Common Android APIs 11 Using Android Networking APIs 169 Understanding Mobile Networking Fundamentals 169 Understanding Strict Mode with Networking 170 Accessing the Internet (HTTP) 170