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, ranging from the mostly defunct Openmoko FreeRunner to QT Embedded, Moblin, LiMo, Debian Mobile, and Maemo to the recently open sourced Symbian OS and the recently defunct HP WebOS. And let’s not forget the established closed source stalwarts: BlackBerry OS, Apple’s iPhone, and Microsoft Windows Mobile (these all have developer toolkits, but their OS is not available as open source and often has other “click-wrap” restrictions).
“Nobody’s armchair is a good predictor of the future,” though, as Mike O’Dell once said. Does Android have a place in the sun alongside these other players? We thought it did when we set out to crowdsource this book, and time has proven us right: Android is definitely here to stay! This book is here to help the Android developer community share the knowledge that will make it happen. Those who contribute knowledge here are helping to make Android development easier for those who come after.
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 and the reliability and portability of a standard high-level language and API. Android apps are written in the Java language, using tools such as Eclipse, compiled against the Android API, and translated into bytecode for the Dalvik VM.
Android is thus related by OS family to Openmoko, QT Embedded, MeeGo (the 2010 merger of Nokia’s Maemo and Intel’s MobLin: http://www.engadget.com/2010/02/15/meego-nokia-and-intel-merge-maemo-and-moblin), OPhone, LiMo, and other Linux-based cell phone projects. Android is also related by programming language to BlackBerry and Java ME phones, and to Java and the wider realm of Java Enterprise applications.
Android sales have continued to climb; a report from NPD states that first-quarter 2010 sales of all Android devices exceeded sales of the iPhone, moving Android into second place (although still well behind the BlackBerry platform). Surely its growth was due in part to major carrier Verizon’s two-for-one sale, but that doesn’t account for all of it…
This book was written by several dozen Android developers from the Android community at large. Development occurred in the open, on the website http://androidcookbook.com/, which I built 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 moved this book from a dream to the reality that you have in your hands (or on-screen if you are reading the ebook format). Thank you all!
We assume you know the basics of the Java language. If not, see Recipe 1.2. 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. If not, see Recipe 1.6.
Chapter 1, Getting Started, 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, Designing a Successful Application, 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, Testing. 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
an application and across applications. In Chapter 4, Inter-/Intra-Process Communication we discuss intents and broadcast
AsyncTasks, and handlers.
Another communication mechanism is about allowing controlled access to data that is usually in an SQL database. In Chapter 5, Content Providers, we show you how to make an application that can be used by other applications through something as simple but ubiquitous (in Android) as the URL.
Chapter 6, Graphics, 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 7, Graphical User Interface, 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 8, GUI Alerts: Menus, Dialogs, Toasts, and Notifications, 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.
Chapter 9, GUI: ListView, focuses on
one of the most important GUI components in Android, the
Android is rich in multimedia capabilities. Chapter 10, Multimedia, shows how to use the most important of these.
Chapter 11, Data Persistence, shows how to save data into files, databases, and so on. And how to retrieve it later, of course.
Android started out as an operating system for mobile telephones. Chapter 12, Telephone Applications, shows how to control and react to the telephone device 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 13, Networked Applications, shows the coding for traditional networked applications. This is followed by Chapter 14, Gaming and Animation, and Chapter 15, Social Networking.
The now-ubiquitous Global Positioning System has also had a major impact on how mobile applications work. Chapter 16, Location and Map Applications, discusses how to find your 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 17, Accelerometer, talks about the sensors built into most Android devices and how to use them.
Chapter 18, Bluetooth, 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 19, System and Device Control. Since Android is Linux-based, a few of the recipes in this chapter deal with traditional Unix/Linux commands and facilities.
In Chapter 20, Other Programming Languages and Frameworks, 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 21, Strings and Internationalization, goes over the issues of language and culture and how they relate to Android.
Most Android developers hope other people will use their applications. But this won’t happen if users can’t find the applications. Chapter 22, Packaging, Deploying, and Distributing/Selling Your App, shows how to prepare your application for distribution via the Android Market, and to use that as well as other markets to get your application out to the people who will use it.
The following typographical conventions are used in this book:
Indicates new terms, URLs, email addresses, filenames, and file extensions.
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 icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Contributors of each recipe have the option to provide a download
URL for their source code. Additionally, some recipes feature an
individual source download, listed both as a hyperlink for PDF users and
as a QR-format barcode for downloading from the printed edition. These
URLs are included at the end of each recipe. In each case the archive file
is expected to contain a complete Eclipse project. The archives are also
collected and published at the book’s GitHub site, which can be found at
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, but
the ZIP will download more quickly.
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, edited by Ian F. Darwin (O’Reilly). Copyright 2012 O’Reilly Media, Inc., 978-1-449-38841-6.”
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at firstname.lastname@example.org.
Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com.
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)|
We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:
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: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://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 this book: Amir Alagic, Jim Blackler, Luis Vitorio Cargnini, Rupesh Chavan, Adrian Cowham, Nidhin Jose Davis, Wagied Davids, 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, 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.
I must also mention the many people at O’Reilly who have helped shape this book, including my editors Mike Loukides, Courtney Nash, and Meghan Blanchette; Adam Witwer and Sarah Schneider in production; production editor Teresa Elsey, who shepherded the whole production process; external copy editor 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!
My son Andrej Darwin helped with some administrative tasks late in the recipe editing phase. 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.
To all of the above, thank you!