Table Of ContentCompanion
BOOKS FOR PROFESSIONALS BY PROFESSIONALS® eBook
Hundreds of problems and solutions of code recipes
Available
using Android 5.0
Android Recipes, Fourth Edition offers more than 100 down-to-earth code recipes,
and guides you step-by-step through a wide range of useful topics using complete
and real-world working code examples. This book is updated to include the Android 5.0
SDK - including the new Android Wear and TV SDKs - as well as earlier releases.
Instead of abstract descriptions of complex concepts, in Android Recipes, you’ll find live
code examples. When you start a new project you can consider copying and pasting
the code and configuration files from this book and then modifying them for your own
customization needs.
A
Crammed with insightful instruction and helpful examples, this fourth edition of
Android Recipes is your guide to writing apps for one of today’s hottest mobile platforms.
It offers pragmatic advice that will help you get the job done quickly and well. This can n
save you a great deal of work over creating a project from scratch!
•
Code for Android smartphones, tablets and now wearables and TV apps
• d
Use external libraries to save time and effort
•
Boost app performance by using the Android NDK and RenderScript
•
Design apps for performance, responsiveness, and seamlessness
• r
Send data between devices and other external hardware
•
Persist application data and share it between applications o
•
Capture and play back various device media items
•
Communicate with web services
• Get the most out of your user interface i
d
R AAnnddrrooiidd
e
c
i
p
e
s Recipes
A Problem-Solution Approach
FOURTH
EDITION
FOURTH EDITION
S
m
i Dave Smith
t
h
COMPANION eBOOK
ISBN 978-1-4842-0476-4
US $49.99 54999
Shelve in
Mobile Computing
SOURCE CODE ONLINE
User level:
www.apress.com Intermediate 9781484204764
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
Contents at a Glance
About the Author ����������������������������������������������������������������������������������������������������xxi
About the Technical Reviewer ������������������������������������������������������������������������������xxiii
Acknowledgments �������������������������������������������������������������������������������������������������xxv
Introduction ���������������������������������������������������������������������������������������������������������xxvii
■ Chapter 1: Layouts and Views �������������������������������������������������������������������������������1
■ Chapter 2: User Interaction Recipes ��������������������������������������������������������������������89
■ Chapter 3: Communications and Networking ����������������������������������������������������199
■ Chapter 4: Interacting with Device Hardware and Media ����������������������������������289
■ Chapter 5: Persisting Data ���������������������������������������������������������������������������������391
■ Chapter 6: Interacting with the System �������������������������������������������������������������471
■ Chapter 7: Graphics and Drawing ����������������������������������������������������������������������613
■ Chapter 8: Working with Android NDK and RenderScript ����������������������������������689
Index ���������������������������������������������������������������������������������������������������������������������737
iii
Introduction
Welcome to the fourth edition of Android Recipes!
If you are reading this book, you probably don’t need to be told of the immense opportunity
that mobile devices represent for software developers and users. In recent years, Android
has become one of the top mobile platforms for device users. This means that you, as a
developer, must know how to harness Android so you can stay connected to this market
and the potential that it offers. But any new platform brings with it uncertainty about best
practices and solutions to common needs and problems.
What we aim to do with Android Recipes is give you the tools to write applications for the
Android platform through direct examples targeted at the specific problems you are trying
to solve. This book is not a deep dive into the Android SDK, NDK, or any of the other tools.
We don’t weigh you down with all the details and theory behind the curtain. That’s not to
say that those details aren’t interesting or important. You should take the time to learn them,
as they may save you from making future mistakes. However, more often than not, they are
simply a distraction when you are just looking for a solution to an immediate problem.
This book is not meant to teach you Java programming or even the building blocks of an
Android application. You won’t find many basic recipes in this book (such as how to display
text with TextView, for instance), as we feel these are tasks easily remembered once learned.
Instead, we set out to address tasks that developers, once comfortable with Android, need
to do often but find too complex to accomplish with a few lines of code.
Treat Android Recipes as a reference to consult, a resource-filled cookbook that you can
always open to find the pragmatic advice you need to get the job done quickly and well.
xxvii
xxviii Introduction
What Will You Find in the Book?
We dive into using the Android SDK to solve real problems. You will learn tricks for effectively
creating a user interface that runs well across device boundaries. You will become a master
at incorporating the collection of hardware (radios, sensors, and cameras) that makes
mobile devices unique platforms. We’ll even discuss how to make the system work for you
by integrating with the services and applications provided by Google and various device
manufacturers.
Performance matters if you want your applications to succeed. Most of the time, this isn’t
a problem because the Android runtime engines get progressively better at compiling
bytecode into the device’s native code. However, you might need to leverage the Android
NDK to boost performance. Chapter 8 offers you an introduction to the NDK and integrating
native code into your application using Java Native Interface (JNI) bindings.
The NDK is a complex technology, which can also reduce your application’s portability.
Also, while good at increasing performance, the NDK doesn’t address multicore processing
very well for heavy workloads. Fortunately, Google has eliminated this tedium and simplified
the execute-on-multiple-cores task while achieving portability by introducing RenderScript.
Chapter 8 introduces you to RenderScript and shows you how to use its compute engine
(and automatically leverage CPU cores) to process images.
Keep a Level Eye on the Target
Throughout the book, you will see that we have marked most recipes with the minimum API
level that is required to support them. Most of the recipes in this book are marked API Level 1,
meaning that the code used can be run in applications targeting any version of Android
since 1.0. However, where necessary, we use APIs introduced in later versions. Pay close
attention to the API level marking of each recipe to ensure that you are not using code that
doesn’t match up with the version of Android your application is targeted to support.
1
Chapter
Layouts and Views
The Android platform is designed to operate on a variety of device types, screen sizes,
and screen resolutions. To assist developers in meeting this challenge, Android provides a
rich toolkit of user interface (UI) components to utilize and customize to the needs of their
specific applications. Android also relies heavily on an extensible XML framework and set
resource qualifiers to create liquid layouts that can adapt to these environmental changes.
In this chapter, we take a look at some practical ways to shape this framework to fit your
specific development needs.
1-1. Styling Common Components
Problem
You want to create a consistent look and feel for your application across all the versions of
Android your users may be running, while reducing the amount of code required to maintain
those customizations.
Solution
(API Level 1)
You can abstract common attributes that define the look and feel of your application views
into XML styles. Styles are collections of view attribute customizations, such as text size
or background color, that should be applied to multiple views throughout the application.
Abstracting these attributes into a style allows the common elements to be defined in a
single location, making the code easier to update and maintain.
Android also supports grouping multiple styles together in a global element called a theme.
Themes apply to an entire context (such as an activity or application), and define styles that
should apply to all the views within that context. Every activity launch in your application has
a theme applied to it, even if you don’t define one. In such cases, the default system theme
is applied instead.
1
2 CHAPTER 1: Layouts and Views
How It Works
To explore the styles concept, let’s create an activity layout that looks like Figure 1-1.
Figure 1-1. Styled widgets
As you can see, this view has some elements that we want to customize to look different
than they normally do with the styling from the default system theme applied. One option
would be to define all the attributes for all the views directly in our activity layout. If we were
to do so, it would look like Listing 1-1.
Listing 1-1. res/layout/activity_styled.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textStyle="bold"
android:text="Select One"/>
CHAPTER 1: Layouts and Views 3
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="@dimen/buttonHeight"
android:button="@null"
android:background="@drawable/background_radio"
android:gravity="center"
android:text="One"/>
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="@dimen/buttonHeight"
android:button="@null"
android:background="@drawable/background_radio"
android:gravity="center"
android:text="Two"/>
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:minHeight="@dimen/buttonHeight"
android:button="@null"
android:background="@drawable/background_radio"
android:gravity="center"
android:text="Three"/>
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textStyle="bold"
android:text="Select All"/>
<TableRow>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="@dimen/buttonHeight"
android:minWidth="@dimen/checkboxWidth"
android:button="@null"
android:gravity="center"
android:textStyle="italic"
android:textColor="@color/text_checkbox"
android:text="One"/>
4 CHAPTER 1: Layouts and Views
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="@dimen/buttonHeight"
android:minWidth="@dimen/checkboxWidth"
android:button="@null"
android:gravity="center"
android:textStyle="italic"
android:textColor="@color/text_checkbox"
android:text="Two"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="@dimen/buttonHeight"
android:minWidth="@dimen/checkboxWidth"
android:button="@null"
android:gravity="center"
android:textStyle="italic"
android:textColor="@color/text_checkbox"
android:text="Three"/>
</TableRow>
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="@dimen/buttonWidth"
android:background="@drawable/background_button"
android:textColor="@color/accentPink"
android:text="@android:string/ok"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="@dimen/buttonWidth"
android:background="@drawable/background_button"
android:textColor="@color/accentPink"
android:text="@android:string/cancel"/>
</TableRow>
</TableLayout>
To add emphasis, we’ve highlighted the attributes in each view that are common to other
views of the same type. These are the attributes that make the buttons, text headings, and
checkable elements all look the same. There’s a lot of duplication to make this happen, and
we can clean it up with a style.
First, we need to create a new resource file, and define each attribute group with a <style>
tag. Listing 1-2 shows the completed abstractions.
CHAPTER 1: Layouts and Views 5
Listing 1-2. res/values/styles.xml
<resources>
<!-- Widget Styles -->
<style name="LabelText" parent="android:TextAppearance.Large">
<item name="android:textStyle">bold</item>
</style>
<style name="FormButton" parent="android:Widget.Button">
<item name="android:minWidth">@dimen/buttonWidth</item>
<item name="android:background">@drawable/background_button</item>
<item name="android:textColor">@color/accentPink</item>
</style>
<style name="FormRadioButton" parent="android:Widget.CompoundButton.RadioButton">
<item name="android:minHeight">@dimen/buttonHeight</item>
<item name="android:button">@null</item>
<item name="android:background">@drawable/background_radio</item>
<item name="android:gravity">center</item>
</style>
<style name="FormCheckBox" parent="android:Widget.CompoundButton.CheckBox">
<item name="android:minHeight">@dimen/buttonHeight</item>
<item name="android:minWidth">@dimen/checkboxWidth</item>
<item name="android:button">@null</item>
<item name="android:gravity">center</item>
<item name="android:textStyle">italic</item>
<item name="android:textColor">@color/text_checkbox</item>
</style>
</resources>
A <style> groups together the common attributes we need to apply to each view type.
Views can accept only a single style definition, so all the attributes for that view must be
collected in one group. Styles do support inheritance, however, which allows us to cascade
our definitions of each style before they are applied to the view.
Notice how each style also declares a parent. This is the base framework style that we
should inherit from. Parent styles are not required, but because of the single style rule on
each view, overwriting the default with your custom version replaces the theme’s default.
If you don’t inherit from a base parent, you will be forced to define all the attributes that
view needs. Extending a widget’s style from the framework’s base ensures that we are
responsible only for adding the attributes we want to customize beyond the default theme’s
look and feel.