Statistics
6
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-03-01

AuthorIan F. Darwin

Jump in and build working Android apps with the help of more than 230 tested recipes. The second edition of this acclaimed cookbook includes recipes for working with user interfaces, multitouch gestures, location awareness, web services, and specific device features such as the phone, camera, and accelerometer. You also get useful info on packaging your app for the Google Play Market. Ideal for developers familiar with Java, Android basics, and the Java SE API, this book features recipes contributed by more than three dozen Android developers. Each recipe provides a clear solution and sample code you can use in your project right away. Among numerous topics, this cookbook helps you: • Get started with the tooling you need for developing and testing Android apps • Create layouts with Android’s UI controls, graphical services, and pop-up mechanisms • Build location-aware services on Google Maps and OpenStreetMap • Control aspects of Android’s music, video, and other multimedia capabilities • Work with accelerometers and other Android sensors • Use various gaming and animation frameworks • Store and retrieve persistent data in files and embedded databases • Access RESTful web services with JSON and other formats • Test and troubleshoot individual components and your entire application

Tags
No tags
ISBN: 1449374433
Publisher: O’Reilly Media
Publish Year: 2017
Language: 英文
Pages: 772
File Format: PDF
File Size: 22.8 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Ian F. Darwin Android Cookbook PROBLEMS AND SOLUTIONS FOR ANDROID DEVELOPERS 2nd Edition Covers Android Nougat 7.0
(This page has no text content)
Ian Darwin Android Cookbook Problems and Solutions for Android Developers SECOND EDITION
978-1-449-37443-3 [LSI] Android Cookbook by Ian F. Darwin Copyright © 2017 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://www.oreilly.com/safari). For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Dawn Schanafelt and Meghan Blanchette Production Editor: Colleen Lobner Copyeditor: Kim Cofer Proofreader: Rachel Head Indexer: Judith McConville Interior Designer: David Futato Cover Designer: Randy Comer Illustrator: Rebecca Demarest May 2017: Second Edition Revision History for the Second Edition 2017-05-05: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781449374433 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Android Cookbook, the cover image of a marine iguana, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
To Dennis M. Ritchie (1941–2011), language pioneer and co-inventor of Unix, who showed us all where the braces go, reminded us to keep it simple, and gave us so much more…
(This page has no text content)
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Understanding the Android Application Architecture 1 1.2 Understanding the Android Activity Life Cycle 3 1.3 Learning About Android Releases 5 1.4 Learning the Java Language 7 1.5 Creating a “Hello, World” Application from the Command Line 8 1.6 Creating a “Hello, World” App with Apache Maven 13 1.7 Choosing an IDE for Android Development 15 1.8 Setting Up Android Studio 18 1.9 Installing Platform Editions and Keeping the SDK Updated 21 1.10 Creating a “Hello, World” App Using Android Studio 25 1.11 Converting an Eclipse ADT Project to Android Studio 30 1.12 Preserving History While Converting from Eclipse to Android Studio 34 1.13 Building an Android Application with both Eclipse and Android Studio 36 1.14 Setting Up Eclipse with AndMore (Replacing ADT) 39 1.15 Creating a “Hello, World” Application Using Eclipse 46 1.16 Installing the Eclipse Marketplace Client in Your Eclipse 51 1.17 Upgrading a Project from Eclipse ADT to Eclipse AndMore 53 1.18 Controlling Emulators/Devices Using Command-Line ADB 57 1.19 Sharing Java Classes from Another Eclipse Project 59 1.20 Referencing Libraries to Implement External Functionality 62 1.21 Using New Features on Old Devices via the Compatibility Libraries 67 1.22 Using SDK Samples to Help Avoid Head Scratching 68 1.23 Taking a Screenshot/Video from the Emulator/Android Device 70 1.24 Program: A Simple CountDownTimer Example 76 1.25 Program: Tipster, a Tip Calculator for the Android OS 79 v
2. Designing a Successful Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 2.1 Exception Handling 101 2.2 Requesting Android Permissions at Runtime 104 2.3 Accessing Android’s Application Object as a “Singleton” 106 2.4 Keeping Data When the User Rotates the Device 109 2.5 Monitoring the Battery Level of an Android Device 111 2.6 Creating Splash Screens in Android 113 2.7 Designing a Conference/Camp/Hackathon/Institution App 117 2.8 Using Google Analytics in an Android Application 119 2.9 Setting First-Run Preferences 122 2.10 Formatting Numbers 123 2.11 Formatting with Correct Plurals 127 2.12 Formatting the Time and Date for Display 130 2.13 Simplifying Date/Time Calculations with the Java 8 java.time API 132 2.14 Controlling Input with KeyListeners 134 2.15 Backing Up Android Application Data 137 2.16 Using Hints Instead of Tool Tips 144 3. Application Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 3.1 Setting Up an Android Virtual Device (AVD) for App Testing 148 3.2 Testing on a Wide Range of Devices with Cloud-Based Testing 154 3.3 Testing with Eclipse and JUnit 155 3.4 Testing with Android Studio and JUnit 158 3.5 Testing with Robolectric and JUnit 4 163 3.6 Testing with ATSL, Espresso, and JUnit 4 166 3.7 Troubleshooting Application Crashes 170 3.8 Debugging Using Log.d() and LogCat 173 3.9 Getting Bug Reports Automatically with Crash Reporting 175 3.10 Using a Local Runtime Application Log for Analysis of Field Errors or Situations 178 3.11 Reproducing Activity Life-Cycle Scenarios for Testing 181 3.12 Keeping Your App Snappy with StrictMode 186 3.13 Static Code Testing with Android Lint 187 3.14 Dynamic Testing with the Monkey Program 189 3.15 Sending Text Messages and Placing Calls Between AVDs 191 4. Inter-/Intra-Process Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 4.1 Opening a Web Page, Phone Number, or Anything Else with an Intent 194 4.2 Emailing Text from a View 196 4.3 Sending an Email with Attachments 199 4.4 Pushing String Values Using Intent.putExtra() 201 4.5 Retrieving Data from a Subactivity Back to Your Main Activity 202 vi | Table of Contents
4.6 Keeping a Background Service Running While Other Apps Are on Display 205 4.7 Sending/Receiving a Broadcast Message 207 4.8 Starting a Service After Device Reboot 208 4.9 Creating a Responsive Application Using Threads 209 4.10 Using AsyncTask to Do Background Processing 210 4.11 Sending Messages Between Threads Using an Activity Thread Queue and Handler 218 4.12 Creating an Android Epoch HTML/JavaScript Calendar 220 5. Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 5.1 Using a Custom Font 227 5.2 Drawing a Spinning Cube with OpenGL ES 230 5.3 Adding Controls to the OpenGL Spinning Cube 234 5.4 Freehand Drawing Smooth Curves 237 5.5 Taking a Picture Using an Intent 242 5.6 Taking a Picture Using android.media.Camera 244 5.7 Scanning a Barcode or QR Code with the Google ZXing Barcode Scanner 248 5.8 Using AndroidPlot to Display Charts and Graphs 251 5.9 Using Inkscape to Create an Android Launcher Icon from OpenClipArt.org 254 5.10 Using Paint.NET to Create Launcher Icons from OpenClipArt.org 259 5.11 Using Nine Patch Files 267 5.12 Creating HTML5 Charts with Android RGraph 270 5.13 Adding a Simple Raster Animation 274 5.14 Using Pinch to Zoom 278 6. Graphical User Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 6.1 Understanding and Following User Interface Guidelines 282 6.2 Looking Good with Material Design 283 6.3 Choosing a Layout Manager (a.k.a. ViewGroup) and Arranging Components 287 6.4 Handling Configuration Changes by Decoupling the View from the Model 288 6.5 Controlling the Action Bar 291 6.6 Adding a Share Action to Your Action Bar 295 6.7 Building Modern UIs with the Fragment API 299 6.8 Creating a Button and Its Click Event Listener 304 6.9 Enhancing UI Design Using Image Buttons 305 6.10 Using a FloatingActionButton 306 6.11 Wiring Up an Event Listener in Many Different Ways 309 6.12 Using CheckBoxes and RadioButtons 314 6.13 Using Card Widgets 318 6.14 Offering a Drop-Down Chooser via the Spinner Class 320 Table of Contents | vii
6.15 Handling Long-Press/Long-Click Events 323 6.16 Displaying Text Fields with TextView and EditText 324 6.17 Constraining EditText Values with Attributes and the TextWatcher Interface 325 6.18 Implementing AutoCompleteTextView 328 6.19 Feeding AutoCompleteTextView Using a SQLite Database Query 330 6.20 Turning Edit Fields into Password Fields 332 6.21 Changing the Enter Key to “Next” on the Soft Keyboard 333 6.22 Processing Key-Press Events in an Activity 336 6.23 Let Them See Stars: Using RatingBar 337 6.24 Making a View Shake 341 6.25 Providing Haptic Feedback 342 6.26 Navigating Different Activities Within a TabView 346 6.27 Creating a Loading Screen that Will Appear Between Two Activities 347 6.28 Adding a Border with Rounded Corners to a Layout 349 6.29 Detecting Gestures in Android 351 6.30 Creating a Simple App Widget 358 7. GUI Alerts: Menus, Dialogs, Toasts, Snackbars, and Notifications. . . . . . . . . . . . . . . . . 363 7.1 Alerting the User with Toast and Snackbar 364 7.2 Customizing the Appearance of a Toast 366 7.3 Creating and Displaying a Menu 367 7.4 Handling Choice Selection in a Menu 369 7.5 Creating a Submenu 370 7.6 Creating a Pop-up/Alert Dialog 372 7.7 Using a Timepicker Widget 374 7.8 Creating an iPhone-like WheelPicker for Selection 376 7.9 Creating a Tabbed Dialog 379 7.10 Creating a ProgressDialog 382 7.11 Creating a Custom Dialog with Buttons, Images, and Text 383 7.12 Creating a Reusable “About Box” Class 385 7.13 Creating a Notification in the Status Bar 389 8. Other GUI Elements: Lists and Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 8.1 Building List-Based Applications with RecyclerView 395 8.2 Building List-Based Applications with ListView 399 8.3 Creating a “No Data” View for ListViews 403 8.4 Creating an Advanced ListView with Images and Text 405 8.5 Using Section Headers in ListViews 409 8.6 Keeping the ListView with the User’s Focus 413 8.7 Writing a Custom List Adapter 414 8.8 Using a SearchView to Search Through Data in a ListView 418 viii | Table of Contents
8.9 Handling Orientation Changes: From ListView Data Values to Landscape Charting 420 9. Multimedia. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 9.1 Playing a YouTube Video 425 9.2 Capturing Video Using MediaRecorder 426 9.3 Using Android’s Face Detection Capability 429 9.4 Playing Audio from a File 432 9.5 Playing Audio Without Interaction 435 9.6 Using Speech to Text 437 9.7 Making the Device Speak with Text-to-Speech 438 10. Data Persistence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 10.1 Reading and Writing Files in Internal and External Storage 442 10.2 Getting File and Directory Information 446 10.3 Reading a File Shipped with the App Rather than in the Filesystem 451 10.4 Getting Space Information About the SD Card 453 10.5 Providing a Preference Activity 454 10.6 Checking the Consistency of Default Shared Preferences 459 10.7 Using a SQLite Database in an Android Application 461 10.8 Performing Advanced Text Searches on a SQLite Database 464 10.9 Working with Dates in SQLite 470 10.10 Exposing Non-SQL Data as a SQL Cursor 472 10.11 Displaying Data with a CursorLoader 475 10.12 Parsing JSON Using JSONObject 478 10.13 Parsing an XML Document Using the DOM API 480 10.14 Storing and Retrieving Data via a Content Provider 482 10.15 Writing a Content Provider 483 10.16 Adding a Contact Through the Contacts Content Provider 487 10.17 Reading Contact Data Using a Content Provider 490 10.18 Implementing Drag and Drop 492 10.19 Sharing Files via a FileProvider 496 10.20 Backing Up Your SQLite Data to the Cloud with a SyncAdapter 501 10.21 Storing Data in the Cloud with Google Firebase 510 11. Telephone Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517 11.1 Doing Something When the Phone Rings 517 11.2 Processing Outgoing Phone Calls 521 11.3 Dialing the Phone 525 11.4 Sending Single-part or Multipart SMS Messages 527 11.5 Receiving an SMS Message 529 11.6 Using Emulator Controls to Send SMS Messages to the Emulator 531 Table of Contents | ix
11.7 Using Android’s TelephonyManager to Obtain Device Information 532 12. Networked Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543 12.1 Consuming a RESTful Web Service Using a URLConnection 544 12.2 Consuming a RESTful Web Service with Volley 547 12.3 Notifying Your App with Google Cloud Messaging “Push Messaging” 549 12.4 Extracting Information from Unstructured Text Using Regular Expressions 558 12.5 Parsing RSS/Atom Feeds Using ROME 559 12.6 Using MD5 to Digest Clear Text 564 12.7 Converting Text into Hyperlinks 565 12.8 Accessing a Web Page Using a WebView 566 12.9 Customizing a WebView 567 12.10 Writing an Inter-Process Communication Service 568 13. Gaming and Animation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 13.1 Building an Android Game Using flixel-gdx 576 13.2 Building an Android Game Using AndEngine 580 13.3 Processing Timed Keyboard Input 587 14. Social Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589 14.1 Authenticating Users with OAUTH2 589 14.2 Integrating Social Networking Using HTTP 593 14.3 Loading a User’s Twitter Timeline Using HTML or JSON 596 15. Location and Map Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 15.1 Getting Location Information 599 15.2 Accessing GPS Information in Your Application 601 15.3 Mocking GPS Coordinates on a Device 603 15.4 Using Geocoding and Reverse Geocoding 606 15.5 Getting Ready for Google Maps API V2 Development 607 15.6 Using the Google Maps API V2 612 15.7 Displaying Map Data Using OpenStreetMap 618 15.8 Creating Overlays in OpenStreetMap Maps 621 15.9 Using a Scale on an OpenStreetMap Map 623 15.10 Handling Touch Events on an OpenStreetMap Overlay 624 15.11 Getting Location Updates with OpenStreetMap Maps 627 16. Accelerometer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631 16.1 Checking for the Presence or Absence of a Sensor 631 16.2 Using the Accelerometer to Detect Shaking 632 16.3 Checking Whether a Device Is Facing Up or Down 636 x | Table of Contents
16.4 Reading the Temperature Sensor 637 17. Bluetooth. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639 17.1 Enabling Bluetooth and Making the Device Discoverable 639 17.2 Connecting to a Bluetooth-Enabled Device 641 17.3 Accepting Connections from a Bluetooth Device 644 17.4 Implementing Bluetooth Device Discovery 645 18. System and Device Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 18.1 Accessing Phone Network/Connectivity Information 647 18.2 Obtaining Information from the Manifest File 648 18.3 Changing Incoming Call Notification to Silent, Vibrate, or Normal 649 18.4 Copying Text and Getting Text from the Clipboard 652 18.5 Using LED-Based Notifications 652 18.6 Making the Device Vibrate 653 18.7 Determining Whether a Given Application Is Running 654 19. All the World’s Not Java: Other Programming Languages and Frameworks. . . . . . . . . 657 19.1 Learning About Cross-Platform Solutions 658 19.2 Running Shell Commands from Your Application 659 19.3 Running Native C/C++ Code with JNI on the NDK 661 19.4 Getting Started with SL4A, the Scripting Layer for Android 667 19.5 Creating Alerts in SL4A 669 19.6 Fetching Your Google Documents and Displaying Them in a ListView Using SL4A 673 19.7 Sharing SL4A Scripts in QR Codes 676 19.8 Using Native Handset Functionality from a WebView via JavaScript 678 19.9 Building a Cross-Platform App with Xamarin 680 19.10 Creating a Cross-Platform App Using PhoneGap/Cordova 685 20. All the World’s Not English: Strings and Internationalization. . . . . . . . . . . . . . . . . . . . 689 20.1 Internationalizing Application Text 690 20.2 Finding and Translating Strings 693 20.3 Handling the Nuances of strings.xml 695 21. Packaging, Deploying, and Distributing/Selling Your App. . . . . . . . . . . . . . . . . . . . . . . 701 21.1 Creating a Signing Certificate and Using It to Sign Your Application 701 21.2 Distributing Your Application via the Google Play Store 705 21.3 Distributing Your Application via Other App Stores 707 21.4 Monetizing Your App with AdMob 708 21.5 Obfuscating and Optimizing with ProGuard 714 21.6 Hosting Your App on Your Own Server 717 Table of Contents | xi
21.7 Creating a “Self-Updating” App 718 21.8 Providing a Link to Other Published Apps in the Google Play Store 720 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725 xii | Table of Contents
Preface Android is “the open source revolution” applied to cellular telephony and mobile computing. At least, part of the revolution. There have been many other attempts to provide open source cell phones, most of them largely defunct, ranging from the Openmoko Neo FreeRunner to QT Embedded, Moblin, LiMo, Debian Mobile, Maemo, Firefox OS, and Ubuntu Mobile to the open sourced Symbian OS and the now-defunct HP WebOS. And let’s not forget the established closed source stalwart, Apple’s iOS, and the two minor players (by market share), Microsoft’s Windows Phone, and the now-abandoned BlackBerry OS 10. Amongst all these offerings, two stand out as major players. Android is definitely here to stay! Due to its open source licensing, Android is used on many economy- model phones around the world, and indeed, Android has been estimated to be on as many as 90% of the world’s smartphones. This book is here to help the Android developer community share the knowledge that will help make better apps. Those who contribute knowledge here are helping to make Android development easier for those who come after. About Android Android is a mobile technology platform that provides cell phones, tablets, and other handheld and mobile devices (even netbooks) with the power and portability of the Linux operating system, the reliability and portability of a standard high-level lan‐ guage and API, and a vast ecosystem of useful applications. Android apps are mostly written in the Java language (using tools such as Eclipse and Android Studio), com‐ piled against the Android API, and translated into bytecode for an Android-specific VM. Android is thus related by OS family to other Linux-based cell phone projects. Android is also related by programming language to BlackBerry’s older Java ME phones, and to Java and the wider realm of Java Enterprise applications. Not to men‐ tion that all current BlackBerry devices can run Android applications, and, in fact, xiii
before it outsourced the remains of its smartphone business, BlackBerry’s last devices only ran Android. It’s now generally believed that Android has almost three-quarters of the world smartphone market, although it has not displaced Apple’s iPad in the tablet market. Sales figures change all the time, but it is clear that Android is, and will remain, one of the dominant players in the mobile space. Android is also available for several specialized platforms. Android Wear brings Android’s programming model to the smartwatch and wearable environment for uses such as fitness trackers. Android Auto is designed for controlling the entertainment units in automobiles. Android TV runs in smart TVs and controllers for not-so- smart TVs. Finally, Android Things is designed for the embedded market, now known as “the internet of things” (IoT). Each of these platforms is fascinating, but to keep the book to a reasonable size, we focus primarily on “regular Android,” Android for smartphone and tablet applications. Who This Book Is By This book was co-written by several dozen Android developers from the Android community at large. Development occurred in the open, on the Android Cookbook website, which I built (using Java, of course) to allow people to contribute, view, review, and comment on the recipes that would make up this book. A complete list can be found in “Acknowledgments” on page xxi. I am deeply grateful to all the con‐ tributors, who have helped move this book from a dream to the reality that you have in your hands (or onscreen if you are reading the ebook format). Thank you all! Who This Book Is For This book focuses on building Android applications using Java, the native language of Android applications. It is of course possible to package up a web application as a mobile app (see Recipe 19.10), but it will be difficult to get the all-important 100%- correct user experience with all the current features of Android that way. So. Java. We assume you know the basics of the Java language. If not, see Recipe 1.4. We also assume you know the basics of the Java Standard Edition API (since this forms the basis of Android’s runtime libraries) as well as the basics of Android. The terms Activity, Intent, Service, and content provider, while not necessarily being what you dream about at night, should at least be familiar to you. But if not, we’ve got you covered: see Recipe 1.2. This book differs from the Samples associated with the Android SDK in that it tries to focus more on how a given piece of technology works, rather than giving you (as many of the Samples do) a complete, working example that has both been simplified xiv | Preface
(to use very simple data) and complicated by adding in several “neat” features that are irrelevant to the problem at hand. What’s in This Book? Chapter 1 takes you through the steps of setting up the Android development envi‐ ronment and building several simple applications of the well-known “Hello, World” type pioneered by Brian Kernighan. Chapter 2 covers some of the differences in mobile computing that will hit developers coming from desktop and enterprise software environments, and talks about how mobile design (in particular, Android design) differs from those other environments. Testing is often an afterthought for some developers, so we discuss this early on, in Chapter 3. Not so that you’ll skip it, but so that you’ll read and heed. We talk about unit testing individual components as well as testing out your entire application in a well-controlled way. Android provides a variety of mechanisms for communicating within and across applications. In Chapter 4 we discuss Intents and broadcast receivers, Services, AsyncTasks, and handlers. Chapter 5 covers a range of topics related to graphics, including use of the graphical drawing and compositing facilities in Android as well as using desktop tools to develop graphical images, textures, icons, and so on that will be incorporated into your finished application. Every mobile app needs a GUI, so Chapter 6 covers the main ins and outs of GUI development for Android. Examples are given both in XML and, in a few cases, in Java-coded GUI development. Chapter 7 covers all the pop-up mechanisms—menus, dialogs, and toasts—and one that doesn’t pop up but is also for interaction outside your application’s window, Android’s notification mechanism. Lists of items are very common in mobile applications on all platforms. Chapter 8 focuses on the “list” components in Android: the ListView and its newer replacement, the RecyclerView. Android is rich in multimedia capabilities. Chapter 9 shows how to use the most important of these. Chapter 10 shows how to save data into files, databases, and so on—and how to retrieve it later, of course. Another communication mechanism is about allowing controlled access to data that is usually in a SQL database. This chapter also shows you how to make application data available to other applications through something Preface | xv
as simple but ubiquitous (in Android) as the URL, and how to use various cloud- based services to store data. Android started out as an operating system for mobile telephones. Chapter 11 shows how to control and react to the telephony component that is in most mobile devices nowadays. Mobile devices are, for the most part, always-on and always-connected. This has a major impact on how people use them and think about them. Chapter 12 shows the coding for traditional networked applications. This is followed by Chapter 13, which discusses gaming and animation, and Chapter 14, which discusses social networking. The now-ubiquitous Global Positioning System (GPS) has also had a major impact on how mobile applications work. Chapter 15 discusses how to find a device’s loca‐ tion, how to get map data from Google and OpenStreetMap, and how applications can be location-aware in ways that are just now being explored. Chapter 16 talks about the sensors built into most Android devices and how to use them. Chapter 17 talks about the low-energy very-local area networking that Bluetooth ena‐ bles, going beyond connecting your Bluetooth headset to your phone. Android devices are perhaps unique in how much control they give the developer. Some of these angles are explored in Chapter 18. Because Android is Linux-based, a few of the recipes in this chapter deal with traditional Unix/Linux commands and facilities. In Chapter 19, we explore the use of other programming languages to write all or part of your Android application. Examples include C, Perl, Python, Lisp, and other lan‐ guages. While this edition of this book is in English, and English remains the number-one technical language worldwide, it is far from the only one. Most end users would rather have an application that has its text in their language and its icons in a form that is culturally correct for them. Chapter 20 goes over the issues of language and culture and how they relate to Android. xvi | Preface
Finally, most Android developers hope other people will use their applications. But this won’t happen if users can’t find the applications. Chapter 21 shows how to pre‐ pare your application for distribution via the Google Play Store, and to use that as well as other markets to get your application out to the people who will use it. Content Updates—Second Edition, March 2017 Major revision for Android Nougat (7.x). As befits a major revision, there are numer‐ ous new recipes to cover all the APIs that have been added or replaced over the past several releases of Android. Of necessity, a few older recipes were retired. Some rec‐ ipes were moved around, which resulted in renumbering of most of the chapters. The Android O Preview was released in the final week of this edition’s proofing stage, and a few references are made to Android O; these should be regarded as “forward- looking statements,” as “O” is still in a preview release. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. Preface | xvii
This element signifies a warning or caution. And here is our first warning: the term “I” used in a given recipe reflects the opinions or experience of that recipe’s contributor, not necessarily of the book’s editor. Getting and Using the Code Examples The code examples in this book vary from a few lines pasted from a complete applica‐ tion through to fully working apps. For those at the “few lines” end of the spectrum, you should not expect to be able to compile them from what we provide; these are intended to be merged into your application. All the examples that we have code for and that are compilable have been merged into a single GitHub repository, which is the recommended way of getting the source code and keeping it up-to-date. This reposi‐ tory can be accessed at https://github.com/IanDarwin/Android-Cookbook-Examples. Each directory in the repo contains one example program’s project. As you will see if you visit this page, GitHub allows you to check out the source repository using the git clone command. As well, the web page offers the option to download the entire repos‐ itory as a single (large) ZIP file as well as to browse portions of the repository in a web browser. Using Git will allow you to receive corrections and updates. Contributors of each recipe also have the option to provide a download URL for their source code, hosted on some other public repository. These are listed as hyperlinks for ebook users to download from at the end of each recipe. In each case the archive file is expected to contain a complete Eclipse or Android Studio project. We have no control over these other repositories, so if one of them is incomplete, or stops work‐ ing, please refer to the GitHub repository instead. Almost all code examples originally written for Eclipse now also contain a build.gradle file so they can be opened directly in Android Studio as well (see Recipe 1.12 to see how we did this). Code examples originally written for Android Studio can, in gen‐ eral, not be used by Eclipse without reorganizing the project struc‐ ture. xviii | Preface