Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Android recipes
Nội dung xem thử
Mô tả chi tiết
COMPANION eBOOK
US $49.99
Shelve in
Mobile Computing
User level:
www.apress.com Intermediate
BOOKS FOR PROFESSIONALS BY PROFESSIONALS®
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.
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
save you a great deal of work over creating a project from scratch!
• Code for Android smartphones, tablets and now wearables and TV apps
• 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
• Send data between devices and other external hardware
• Persist application data and share it between applications
• Capture and play back various device media items
• Communicate with web services
• Get the most out of your user interface
Companion
eBook
Available
SOURCE CODE ONLINE
FOURTH
EDITION Smith
Android
Recipes
Dave Smith
A Problem-Solution Approach
Recipes Android
Android
FOURTH EDITION
Hundreds of problems and solutions of code recipes
using Android 5.0
9 781484 204764
54999
ISBN 978-1-4842-0476-4
www.it-ebooks.info
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.
www.it-ebooks.info
iii
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
www.it-ebooks.info
xxvii
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.
www.it-ebooks.info
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.
www.it-ebooks.info
1
Chapter 1
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.
www.it-ebooks.info
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"/>
www.it-ebooks.info
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"/>
www.it-ebooks.info
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.
www.it-ebooks.info
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.
www.it-ebooks.info
6 CHAPTER 1: Layouts and Views
EXPLICIT VS. IMPLICIT PARENTING
Style inheritance takes one of two forms. A style can explicitly declare its parent, as we’ve seen before:
<style name="BaseStyle" />
<style name="NewStyle" parent="BaseStyle" />
NewStyle is an extension of BaseStyle, and includes all the attributes defined in the parent. Styles also
support an implicit parenting syntax as follows:
<style name="BaseStyle" />
<style name="BaseStyle.Extended" />
In the same way, BaseStyle.Extended inherits its attributes from BaseStyle. The functionality of this
version is identical to the explicit example, just in a more compact convention. The two forms should never be
mixed, and doing so doesn’t allow for multiple parents on a single style. When this is done, the explicit parent
always wins anyway, and the readability of the code is reduced.
We can apply the new styles to our original layout file, and the cleaner result is shown in
Listing 1-3.
Listing 1-3. 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:textAppearance="@style/LabelText"
android:text="Select One"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
style="@style/FormRadioButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="One"/>
www.it-ebooks.info
CHAPTER 1: Layouts and Views 7
<RadioButton
style="@style/FormRadioButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Two"/>
<RadioButton
style="@style/FormRadioButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Three"/>
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="@style/LabelText"
android:text="Select All"/>
<TableRow>
<CheckBox
style="@style/FormCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="One"/>
<CheckBox
style="@style/FormCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Two"/>
<CheckBox
style="@style/FormCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three"/>
</TableRow>
<TableRow>
<Button
style="@style/FormButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@android:string/ok"/>
<Button
style="@style/FormButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@android:string/cancel"/>
</TableRow>
</TableLayout>
www.it-ebooks.info
8 CHAPTER 1: Layouts and Views
By applying a style attribute to each view, we can remove the explicit attribute references
that were duplicated in favor of a single reference on each element. The one exception to
this behavior is our TextView headings, which accept a special android:textAppearance
attribute. This attribute takes a style reference, and applies only to text-formatting attributes
(size, style, color, and so forth). When used, a TextView still allows a separate style attribute
to be applied concurrently. In this way, it is the one supported instance in the framework of
multiple styles on a single view.
Themes
A theme in Android is a type of appearance style that is applicable to an entire application or
activity. There are two choices when applying a theme: use a system theme or create a custom
one. In either case, a theme is applied in the AndroidManifest.xml file, as shown in Listing 1-4.
Listing 1-4. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
<!—Apply to the application tag for a global theme -->
<application android:theme="APPLICATION_THEME_NAME"
...>
<!—Apply to the activity tag for an individual theme -->
<activity android:name=".Activity"
android:theme="ACTIVITY_THEME_NAME"
...>
<intent-filter>
...
</intent-filter>
</activity>
</application>
</manifest>
System Themes
The styles.xml and themes.xml files packaged with the Android framework include a few
options for themes with some useful custom properties. Referencing R.style in the SDK
documentation will provide the full list, but here are a few useful examples:
Theme.Light: Variation on the standard theme that uses an inverse
color scheme for the background and user elements. This is the default
recommended base theme for applications prior to Android 3.0.
Theme.NoTitleBar.Fullscreen: Removes the title bar and status bar, filling
the entire screen (minus any onscreen controls that may be present).
Theme.Dialog: A useful theme to make an activity look like a dialog box.
Theme.Holo.Light: (API Level 11) Theme that uses an inverse color
scheme and that has an action bar by default. This is the default
recommended base theme for applications on Android 3.0.
www.it-ebooks.info
CHAPTER 1: Layouts and Views 9
Theme.Holo.Light.DarkActionBar: (API Level 14) Theme with an
inverse color scheme but a dark solid action bar. This is the default
recommended base theme for applications on Android 4.0.
Theme.Material.Light: (API Level 21) Theme with a simplified color
scheme governed by a small palette of primary colors. This theme also
supports tinting of the standard widgets using the supplied primary
colors. This is the default recommended base theme for applications on
Android 5.0.
Note When using the AppCompat Library, other versions for each of these themes should be used
instead (for example, Theme.AppCompat.Light.DarkActionBar).
Listing 1-5 is an example of a system theme applied to the entire application by setting the
android:theme attribute in the AndroidManifest.xml file.
Listing 1-5. Manifest with Theme Set on Application
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
<!—Apply to the application tag for a global theme -->
<application android:theme="Theme.Material.Light"
...>
...
</application>
</manifest>
Custom Themes
Sometimes the provided system choices aren’t enough. After all, some of the customizable
elements in the window are not even addressed in the system options. Defining a custom
theme to do the job is simple.
If there is not one already, create a styles.xml file in the res/values path of the project.
Remember, themes are just styles applied on a wider scale, so they are defined in the same
place. Theme aspects related to window customization can be found in the R.attr reference
of the SDK, but here are the most common items:
android:windowNoTitle: Governs whether to remove the default title bar;
set to true to remove the title bar.
android:windowFullscreen: Governs whether to remove the system
status bar; set to true to remove the status bar and fill the entire screen.
www.it-ebooks.info
10 CHAPTER 1: Layouts and Views
android:windowBackground: Color or drawable resource to apply as a
background.
android:windowContentOverlay: Drawable placed over the window
content foreground. By default, this is a shadow below the status bar.
Set to any resource to use in place of the default status bar shadow, or
null (@null in XML) to remove it.
In addition, the Material themes accept a series of color attributes that are used to tint the
application interface widgets:
android:colorPrimary: Used to tint primary interface elements, like the
action bar and the scrolling edge glow effects. Also affects the recent
tasks title bar color.
android:colorPrimaryDark: Tints the system controls, such as the
status bar background.
android:colorAccent: Default color applied to controls that are focused
or activated.
android:colorControlNormal: Override color for controls that are not
focused or activated.
android:colorControlActivated: Override color for focused and
activated controls. Takes place of the accent color if both are defined.
android:colorControlHighlight: Override color for controls that are
being pressed.
Listing 1-6 is an example of a styles.xml file that creates a custom theme in order to supply
brand-specific colors for the application interface.
Listing 1-6. res/values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="BaseAppTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<!-- Action bar background color -->
<item name="colorPrimary">@color/primaryBlue</item>
<!-- Status bar tint color -->
<item name="colorPrimaryDark">@color/primaryDarkBlue</item>
<!-- Default color applied to all focused/activated controls -->
<item name="colorAccent">@color/accentPink</item>
<!-- Unselected controls color -->
<item name="colorControlNormal">@color/controlNormalGreen</item>
<!-- Activated control color; overrides accent -->
<item name="colorControlActivated">@color/controlActivatedGreen</item>
</style>
</resources>
www.it-ebooks.info