Jump in and build working Android apps with the help of more than 200 tested recipes. With this cookbook, you’ll find solutions for working with the user interfaces, multitouch gestures, location awareness, web services, and device features such as the phone, camera, and accelerometer. You also get useful steps on packaging your app for the Android Market.
Ideal for developers familiar with Java, Android basics, and the Java SE API, this book features recipes contributed by more than three dozen developers from the Android community. Each recipe provides a clear solution and sample code you can use in your project right away. Among numerous topics, this cookbook helps you:
Use guidelines for designing a successful Android app
Work with UI controls, effective layouts, and graphical elements
Learn how to take advantage of Android’s rich features in your app
Save and retrieve application data in files, SD cards, and embedded databases
Access RESTful web services, RSS/Atom feeds, and information from websites
Create location-aware services to find locations and landmarks, and situate them on Google Maps and OpenStreetMap
Test and troubleshoot individual components and your entire application
Chapter 1 Getting Started
Introduction: Getting Started
Learning the Java Language
Creating a “Hello, World” Application from the Command Line
Creating a “Hello, World” Application in Eclipse
Setting Up an IDE on Windows to Develop for Android
Understanding the Android Life Cycle
Installing .apk Files onto an Emulator via the ADB
Installing Apps onto an Emulator via SlideME
Sharing Java Classes from Another Eclipse Project
Referencing Libraries to Implement External Functionality
Using SDK Samples to Help Avoid Head Scratching
Keeping the Android SDK Updated
Taking a Screenshot from the Emulator/Android Device
Program: A Simple CountDownTimer Example
Program: Tipster, a Tip Calculator for the Android OS
Chapter 2 Designing a Successful Application
Introduction: Designing a Successful Android Application
Accessing Android’s Application Object as a “Singleton”
Keeping Data When the User Rotates the Device
Monitoring the Battery Level of an Android Device
Creating Splash Screens in Android
Designing a Conference/Camp/Hackathon/Institution App
Using Google Analytics in an Android Application
A Simple Torch/Flashlight
Adapting an Android Phone Application to Be Used on a Tablet
Setting First-Run Preferences
Formatting the Time and Date for Display
Controlling Input with KeyListeners
Backing Up Android Application Data
Using Hints Instead of Tool Tips
Chapter 3 Testing
Doing Test-Driven Development (TDD) in Android
Setting Up an Android Virtual Device (AVD) for App Testing
Testing on a Huge Range of Devices with Cloud-based Testing
Creating and Using a Test Project
Troubleshooting Application Crashes
Debugging Using Log.d and LogCat
Getting Bug Reports from Users Automatically with BugSense
Using a Local Runtime Application Log for Analysis of Field Errors or Situations
Reproducing Activity Life-Cycle Scenarios for Testing
Keeping Your App Snappy with StrictMode
Running the Monkey Program
Sending Text Messages and Placing Calls Between AVDs
Chapter 4 Inter-/Intra-Process Communication
Introduction: Inter-/Intra-Process Communication
Opening a Web Page, Phone Number, or Anything Else with an Intent
Emailing Text from a View
Sending an Email with Attachments
Pushing String Values Using Intent.putExtra()
Retrieving Data from a Subactivity Back to Your Main Activity
Keeping a Service Running While Other Apps Are on Display
Sending/Receiving a Broadcast Message
Starting a Service After Device Reboot
Creating a Responsive Application Using Threads
Using AsyncTask to Do Background Processing
Sending Messages Between Threads Using an Activity Thread Queue and Handler
Chapter 5 Content Providers
Introduction: Content Providers
Retrieving Data from a Content Provider
Writing a Content Provider
Writing an Android Remote Service
Chapter 6 Graphics
Using a Custom Font
Drawing a Spinning Cube with OpenGL ES
Adding Controls to the OpenGL Spinning Cube
Freehand Drawing Smooth Curves
Taking a Picture Using an Intent
Taking a Picture Using android.media.Camera
Scanning a Barcode or QR Code with the Google ZXing Barcode Scanner
Using AndroidPlot to Display Charts and Graphs
Using Inkscape to Create an Android Launcher Icon
Creating Easy Launcher Icons from OpenClipArt.org Using Paint.NET
Using Nine Patch Files
Creating HTML5 Charts with Android RGraph
Adding a Simple Raster Animation
Using Pinch to Zoom
Chapter 7 Graphical User Interface
Understanding and Following User Interface Guidelines
Handling Configuration Changes by Decoupling the View from the Model
Creating a Button and Its Click Event Listener
Wiring Up an Event Listener in Five Different Ways
Using CheckBoxes and RadioButtons
Enhancing UI Design Using Image Buttons
Offering a Drop-Down Chooser via the Spinner Class
Handling Long-Press/Long-Click Events
Displaying Text Fields with TextView and EditText
Constraining EditText Values with Attributes and the TextWatcher Interface
Feeding AutoCompleteTextView Using an SQLite Database Query
Turning Edit Fields into Password Fields
Changing the Enter Key to “Next” on the Soft Keyboard
Processing Key-Press Events in an Activity
Let Them See Stars: Using RatingBar
Making a View Shake
Providing Haptic Feedback
Navigating Different Activities Within a TabView
Creating a Custom Title Bar
Formatting with Correct Plurals
Starting a Second Screen from the First
Creating a Loading Screen That Will Appear Between Two Activities
Using SlidingDrawer to Overlap Other Components
Customizing the SlidingDrawer Component to Animate/Transition from the Top Down
Adding a Border with Rounded Corners to a Layout
Detecting Gestures in Android
Building a UI Using Android 3.0 Fragments in Android 1.6 and Later
Using the Android 3.0 Photo Gallery
Creating a Simple App Widget
Chapter 8 GUI Alerts: Menus, Dialogs, Toasts, and Notifications
Introduction: GUI Alerts
Creating and Displaying a Menu
Handling Choice Selection in a Menu
Creating a Submenu
Creating a Pop-up/Alert Dialog
Using a Timepicker Widget
Creating an iPhone-like Wheel Picker for Selection
Creating a Tabbed Dialog
Creating a ProgressDialog
Creating a Custom Dialog with Buttons, Images, and Text
Creating a Reusable About Box Class
Customizing the Appearance of a Toast
Creating a Notification in the Status Bar
Chapter 9 GUI: ListView
Building List-Based Applications with ListView
Creating a “No Data” View for ListViews
Creating an Advanced ListView with Images and Text
Using Section Headers in ListViews
Keeping the ListView with the User’s Focus
Writing a Custom List Adapter
Handling Orientation Changes: From ListView Data Values to Landscape Charting
Chapter 10 Multimedia
Playing a YouTube Video
Using the Gallery with the ImageSwitcher View
Capturing Video Using MediaRecorder
Using Android’s Face Detection Capability
Playing Audio from a File
Playing Audio Without Interaction
Using Speech to Text
Making the Device Speak with Text-to-Speech
Chapter 11 Data Persistence
Introduction: Data Persistence
Getting File Information
Reading a File Shipped with the App Rather Than in the Filesystem
Listing a Directory
Getting Total and Free Space Information About the SD Card
Providing User Preference Activity with Minimal Effort
Checking the Consistency of Default Shared Preferences
Performing Advanced Text Searches
Creating an SQLite Database in an Android Application
Inserting Values into an SQLite Database
Loading Values from an Existing SQLite Database
Working with Dates in SQLite
Parsing JSON Using JSONObject
Parsing an XML Document Using the DOM API
Parsing an XML Document Using an XmlPullParser
Adding a Contact
Reading Contact Data
Chapter 12 Telephone Applications
Introduction: Telephone Applications
Doing Something When the Phone Rings
Processing Outgoing Phone Calls
Dialing the Phone
Sending Single-Part or Multipart SMS Messages
Receiving an SMS Message in an Android Application
Using Emulator Controls to Send SMS Messages to the Emulator
Using Android’s TelephonyManager to Obtain Device Information
Chapter 13 Networked Applications
Using a RESTful Web Service
Extracting Information from Unstructured Text Using Regular Expressions
Parsing RSS/Atom Feeds Using ROME
Using MD5 to Digest Clear Text
Converting Text into Hyperlinks
Accessing a Web Page Using WebView
Customizing a WebView
Chapter 14 Gaming and Animation
Introduction: Gaming and Animation
Building an Android Game Using flixel-android
Building an Android Game Using AndEngine (Android-Engine)
Processing Timed Keyboard Input
Chapter 15 Social Networking
Introduction: Social Networking
Integrating Social Networking Using HTTP
Loading a User’s Twitter Timeline Using JSON
Chapter 16 Location and Map Applications
Introduction: Location-Aware Applications
Getting Location Information
Accessing GPS Information in Your Application
Mocking GPS Coordinates on a Device
Using Geocoding and Reverse Geocoding
Getting Ready for Google Maps Development
Adding a Device’s Current Location to Google Maps
Drawing a Location Marker on a Google MapView
Drawing Multiple Location Markers on a MapView
Creating Overlays for a Google MapView
Changing Modes of a Google MapView
Drawing an Overlay Icon Without Using a Drawable
Implementing Location Search on Google Maps
Placing a MapView Inside a TabView
Handling a Long-Press in a MapView
Creating Overlays in OpenStreetMap Maps
Using a Scale on an OpenStreetMap Map
Handling Touch Events on an OpenStreetMap Overlay
Getting Location Updates with OpenStreetMap Maps
Chapter 17 Accelerometer
Checking for the Presence or Absence of a Sensor
Using the Accelerometer to Detect Shaking of the Device
Checking Whether a Device Is Facing Up or Facing Down Based on Screen Orientation Using an Accelerometer
Finding the Orientation of an Android Device Using an Orientation Sensor
Reading the Temperature Sensor
Chapter 18 Bluetooth
Enabling Bluetooth and Making the Device Discoverable
Connecting to a Bluetooth-Enabled Device
Listening for and Accepting Bluetooth Connection Requests
Implementing Bluetooth Device Discovery
Chapter 19 System and Device Control
Introduction: System and Device Control
Accessing Phone Network/Connectivity Information
Obtaining Information from the Manifest File
Changing Incoming Call Notification to Silent, Vibrate, or Normal
Copying Text and Getting Text from the Clipboard
Using LED-Based Notifications
Making the Device Vibrate
Running Shell Commands from Your Application
Determining Whether a Given Application Is Running
Chapter 20 Other Programming Languages and Frameworks
Introduction: Other Programming Languages
Running an External/Native Unix/Linux Command
Running Native C/C++ Code with JNI on the NDK
Getting Started with the Scripting Layer for Android (SL4A, Formerly Android Scripting Environment)
Creating Alerts in SL4A
Fetching Your Google Documents and Displaying Them in a ListView Using SL4A
Sharing SL4A Scripts in QR Codes
Creating a Platform-Independent Application Using PhoneGap/Cordova
Chapter 21 Strings and Internationalization
Internationalizing Application Text
Finding and Translating Strings
Handling the Nuances of strings.xml
Chapter 22 Packaging, Deploying, and Distributing/Selling Your App
Introduction: Packaging, Deploying, and Distributing
Creating a Signing Certificate
Signing Your Application
Distributing Your Application via Android Play (formerly the Android Market)
Integrating AdMob into Your App
Obfuscating and Optimizing with ProGuard
Providing a Link to Other Published Apps in the Google Play Market
Ian F. Darwin has worked in the computer industry for three decades. He wrote the freeware file(1) command used on Linux and BSD and is the author of Checking C Programs with Lint, Java Cookbook, and over seventy articles and courses on C and Unix. In addition to programming and consulting, Ian teaches Unix, C, and Java for Learning Tree International, one of the world's largest technical training companies.
The animal on the cover of the Android Cookbook is a marine iguana (Amblyrhynchus cristatus). These lizards are found exclusively in the Galapagos (with a subspecies particular to each island). They are believed to be descended from land iguanas carried to the islands on log rafts from mainland South America.
The marine iguana is the only type of lizard that feeds in the water. Darwin found the reptiles unattractive and awkward, labeling them “disgusting clumsy lizards” and “imps of darkness,” but these streamlined large animals (up to 5 or 6 feet long) are graceful in the water, with flattened tails designed for swimming.
These lizards feed on seaweed and marine algae. They can dive deeply (as far as 50 feet), though their dives are usually shallow, and they can stay underwater for up to an hour (though 5 to 10 minutes is more typical). Like all reptiles, marine iguanas are coldblooded and must regulate their body temperature by basking in the sun; their black or gray coloration maximizes their heat absorption when they come out of the cold ocean. Though these harmless herbivores often allow humans to approach them closely, they can be aggressive when cold.
Marine iguanas have specialized nasal glands that filter ocean salt from their blood. They sneeze up the excess salt, which often accumulates on their heads or faces, creating a distinctive white patch or “wig.” These iguanas are vulnerable to predation by introduced species (including dogs and cats), as well as to ocean pollution and fluctuations in their food supply caused by weather events such as ElNiño.
The cover image is from Wood’s Animate Creation. The cover font is Adobe ITC Garamond. The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is LucasFont’s TheSansMonoCondensed.
This is exactly what you need. I shows you how to write Android apps without much blabla. I've read other Android book before, this one made me productive. Thank$! It is easy to read and understand. Recommended for teaching if you want results (working apps). Android is a moving target, so you need to do your own work on top of it. There's no way around this. This is why I give five stars.
Bottom Line Yes, I would recommend this to a friend
Just started using the book yet my first experiences with Chapter 9 are quite disappointing. The main problem I have is that I was expecting that the recipes from the website are used as the base yet put together and modified in a way that the while cookbook becomes a consistent source of recipes.
Here some things I dislike.
9.2 discourages from using ListActivity for given reasons. (->9.4) 9.3 doesnt give any hint what android:layout_below = "@id/textView1" is about. 9.4 uses the in 9.2 discouraged ListActivity, gives a dead link for the source code 9.5 source code has only a readme.txt, saying "This example still needs to be re-created. " Great, why is it in the book. 9.7 starts the discussion with "It's no secret that the best way to explain something is through an example, so let's dive in." Well I am in the middle of a book of examples. Rather than reading about the concrete example outside the scope of the recipe I would prefer a complete simple example showing the key points. 9.8 not working on my device (2.3.4), I read on the web android:screenOrientation="portrait" prevents onConfigurationChanged to be called (not sure if this is the problem, example useless)
Disappointed that ListFilter etc are not covered.
I am sure the book has much to offer yet it is just not a book, rather it seems it is a non-connected collection of recipes of various authors. I guess I am just spoiled by the Perl Cookbook.
I bought the ebook because I am abroad not always with internet access. If you are online I would recommend stay with the website http://androidcookbook.com/ the book has less to offer.
Bottom Line No, I would not recommend this to a friend
Android Cookbook - Book Review This book talks about the new mobile OS Android. This OS (even if Framework is more appropriate) is widespreading through mobile and embedded devices. As the title suggest, this book use a Cookbook style for explain the concepts. Each problem is treated as a Recipe and is composed by 3 parts:
Problem: few rows to describe the problem that needs to be solved. Solution: few rows that explains briefly what must be done for solve the problem. After reading the book, this is kind of a bookmark for future research in the book and allows the reader to remember how to solve a problem simply reading few lines. Discussion: Here is described the solution in all of its aspect. The code is widely described and everything is covered to let the reader understand the solution.
Because this book covers a lot of problems with their relative solution, I prefered to copy the description of the chapters as appears in the preface of the book instead of described them myself.
What's in This Book?
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.
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 receivers, services, 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.
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 ListView. 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.
Chapter 14, Gaming and Animation.
Chapter 15, Social Networking.
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 allow 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.
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. Examplesinclude C, Perl, Python, Lisp, and other languages.
Chapter 21, Strings and Internationalization, goes over the issues of language and culture and how they relate to Android.
Chapter 22, Packaging, Deploying, and Distributing/Selling Your App, shows how to prepare your application for distribution the Android Market, and to use that as well as other markets to get your application out to the people who will use it.
I've never read an Android book before this one and I was a little bit suspicious about how this book would be comprehensible compared to other books more focused on the whole framework instead of single problems. I remained surprise of how this book is clear even for new comers in the Android world, each problem is discussed perfectly and the discussion part of each problem covers also the paradigms of the Android framework. Has to be noticed that a strong Java background is needed, together with a basic knowledge of the Eclipse IDE. I suggest this book for both new Android developers and expert ones, the former can find in this book an explanation about the Android framework, how to use the framework with real problems and a lot of examples that can be reused for create the application they imagine. The latter can improve their knowledge about topics not treated in their current developments and improve with new functionality their apps.
Bottom Line Yes, I would recommend this to a friend
I have been a big fan of the Cookbooks for various languages and am also a fan of Android Cookbook by Ian F. Darwin. If you know how to program, this is perfect to learn how to program for the Android OS. If there's something specific you need to find out how to do, this has great examples on how to do just about anything. I found it was a great reference to have on hand for those times I had a question about how to figure something out. I would definitely recommend this to anyone that might be on the fence about it. It's a keeper just like my Arduino Cookbook. Disclaimer: This book was received as part of the O'Reilly Blogger Review Program. All comments represent my thoughts and opinions.
Bottom Line Yes, I would recommend this to a friend
Hello, I am Ozgur Cakmak and I will be reviewing Android Cookbook. I got this book via O'Reilly's Blogger review program. I am a Java/C sharp developer who recently built an android application for the place I am working for, so this review will come from a person who endured many trials and tribulations of the Android development world. Before starting let me tell you what I expect from a cookbook, so you may have a clearer picture: I expect it to save my time. Nobody, maybe except for a few person, can know a framework's all internal workings like back of his hand encountering problems is a must. And instead of spending hours in front of Google or Stack Overflow I'd like to find an answer to my problem after I clearly define it into a question. As a short review,whether I recommend this book or not. Yes, yes I would. I wish I had read this book, had this book, in my library a month ago. Not only it would speed up my development, it would save me making coding horrors and create a more sensible code base. Right on, let's get this show on the road then... Chapter 1 offers the basics of Android application development. It starts with a very basic hello world example, done both in console and in eclipse (which seems counterintuitive at first, "why should I need a hello world in a cookbook?", then again if you are going to make a presentation or a talk on Android you will need this. Then it guides you to set up the android development environment. From eclipse setup to getting Android SDK they are all given step by step. Then, what I personally dislike in other android books, it continues on to show how to use SDK examples and provides two example applications, which are a countdown timer and a tip calculating application, which are more complex and usable than Hello world. They help. Because at the very worst you will mostly use the components provided in these examples. You will get data from the user via EditText (think of it like the TextBox component in the .net world), interact with her via buttons, provide data in tables, radio buttons, textviews... Let's head into the chapter 2. After getting your intro in the first chapter the book goes in the detail of how to design your application. I feel until you pass the Exception Handling, the cookbook doesn't start. Then, with the recipe "Keeping data when the user rotates the device" you creep into the territory of questions. You have two options if you had this kind of problem, either you can limit the rotation - which how I was handling it before reading the cookbook - or you can save those information and reuse it after the screen rotates. You see, the android is not like you - for the operating system, the vertical screen and the horizontal one are two separate, different views. So it destroys the vertical one to make room for the horizontal view and vice versa. The recipes are wisely selected. Because as I did, you will hit nearly every of them listed here. Maybe except providing a splash screen, or google analytics usage but keeping track on battery level, application first run preferences, saving the data, handling input from key listeners and how to design a conference app are crucial if you are an android developer. The last one, the recipe on conference app, is a request that will be wanted from you. Maybe not now, not tomorrow but that request will come. Except for a few recipes I've told, this chapter is all golden in its value. I'd have to admit, the first part of this book can be used as the core of a tutorial aimed to create Android coders from java juniors and veterans alike. The other chapters go into detail in very diverse topics, they may be diverse but they are items you will encounter in your life as an Android developer. Maps, handling exceptions, creating a conference app. and others. Because I have to keep this brief I had truncated many details regarding the chapters but, they are good; they have been wisely selected (because the questions I asked in my app development were there! Just there!) and the answers are not beating the bush - they are direct, full of code and explanations. So in short, this book is one of the essential books that has to reside in your library. Although I am a webcast-learning guy I have grokked many important info that should be in my knowledge base prior to building the app. Thanks.
Bottom Line Yes, I would recommend this to a friend