O'Reilly logo

Android Cookbook, 2nd Edition by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required


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 language 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), compiled 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 mention that all current BlackBerry devices can run Android applications, and, in fact, 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”. I am deeply grateful to all the contributors, 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 (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 environment 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 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 location, 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 enables, 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 languages.

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.

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 prepare 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 numerous 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 recipes 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:


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 elements 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 determined by context.


This element signifies a tip or suggestion.


This element signifies a general note.


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 application 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 repository 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 repository 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 working, 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 general, not be used by Eclipse without reorganizing the project structure.

How to Determine How a Project Can Be Built

If a project’s top-level directory contains:

AndroidManifest.xml and .project

It is openable with Eclipse.


It is openable with Android Studio or buildable with command-line Gradle.


It is buildable with command-line Maven (or using Maven inside an IDE).


It might still be buildable with the older Ant build tool.

See Figure P-1 for an example of a typical project layout.

The top level of the Git repository for the examples contains a README file, viewable below the list of files and directories, which summarizes which projects can be built using which tools. Please pay attention to the Notes column, as there may at any time be some known issues with building the examples.

projlayout eclipse
Figure P-1. Project layout for typical Eclipse and Studio projects

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Android Cookbook, Second Edition, by Ian F. Darwin (O’Reilly). Copyright 2017 O’Reilly Media, Inc., 978-1-449-37443-3.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com.

O’Reilly Safari


Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals.

Members have access to thousands of books, training videos, Learning Paths, interactive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others.

For more information, please visit http://oreilly.com/safari.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway North
  • Sebastopol, CA 95472
  • 800-998-9938 (in the United States or Canada)
  • 707-829-0515 (international or local)
  • 707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/android-cookbook-2e.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: https://facebook.com/oreilly

Follow us on Twitter: https://twitter.com/oreillymedia

Watch us on YouTube: https://www.youtube.com/oreillymedia


I would like to thank the dozens of people from the Android community at large who contributed so many of the recipes in the first edition of this book: Amir Alagic, Jim Blackler, Luis Vitorio Cargnini, Rupesh Chavan, Adrian Cowham, Wagied Davids, Nidhin Jose Davis, David Dawes, Enrique Diaz, Marco Dinacci, Claudio Esperanca, Kurosh Fallahzadeh, Daniel Fowler, Jonathan Fuerth, Sunit Katkar, Roger Kind Kristiansen, Vladimir Kroz, Alex Leffelman, Ulysses Levy, Thomas Manthey, Emaad Manzoor, Zigurd Mednieks, Keith Mendoza, Roberto Calvo Palomino, Federico Paolinelli, Johan Pelgrim, Catarina Reis, Mike Rowehl, Pratik Rupwal, Oscar Salguero, Ashwini Shahapurkar, Shraddha Shravagi, Rachee Singh, Saketkumar Srivastav, Corey Sunwold, Kailuo Wang, and Colin Wilcox.

Thanks to Mike Way, who contributed the permissions recipe (Recipe 2.2) for the second edition, and Daniel Fowler for updating several of his recipes for this second edition.

I must also mention the many people at O’Reilly who have helped shape this book, including my editors Mike Loukides, Courtney Nash, Meghan Blanchette, and Dawn Schanafelt; Adam Witwer and Sarah Schneider in production; production editor Teresa Elsey, who shepherded the whole production process; external copyeditor Audrey Doyle, who painstakingly read every word and phrase; Stacie Arellano, who proofread it all again; Lucie Haskins, who added index terms to all those recipes; designers Karen Montgomery and David Futato; illustrators Robert Romano and Rebecca Demarest; and anyone whom I’ve neglected to mention—you know who you are! For the second edition: Colleen Lobner, Kim Cofer, Rachel Head, and Judith McConville.

My late son Andrej Darwin helped with some administrative tasks late in the recipe editing phase of the first edition. Thanks to all my family for their support.

Finally, a note of thanks to my two technical reviewers, Greg Ostravich and Zettie Chinfong, without whom there would be many more errors and omissions than the ones that doubtless remain. Not only that, they both came back for the second edition! Rick Isaacs made another pass and tested many recipes. Thanks also to the many people who pointed out minor errors and omissions in the first printing of the book, especially Anto Jurkovic and Joseph C. Eddy; most of these have been corrected at this time. The errors which surely remain are my own.

To all of the above, thank you!

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required