Thứ Bảy, 22 tháng 12, 2012
Original Effortless - Imtimacy
DEAR ABBY:
My husband, "James," and I have been married only three years. We are both in our 20s.
Everything is really great between us -- except our sex life. As far as he is concerned that's fine,
too, but I am not satisfied. It may seem odd to hear the female wants to have sex more frequently
than a young and healthy male, but that's the case in our relationship.
Abby, I work with the public and I get frequent remarks about what a beautiful woman I am. This
makes it hard for me to believe that I don't attract him at all. I have expressed many times that I
wish we were more intimate. I have even expressed it to him in more than one letter, hoping to
reach him.
I am at a total loss as to how to make him realize how important this is to me. Is there something
wrong with my body? I just don't know who to turn to for advice on this subject. Please help me.
-- SHORT ON INTIMACY IN OHIO
Thứ Tư, 19 tháng 12, 2012
android book 20121220
INTRODUCTION
THIS IS AN EXCITING TIME FOR ANDROID DEVELOPERS. Mobile phones have never been more popu-
lar; powerful smartphones are now a regular choice for consumers; and the Android ecosystem
has expanded to include tablet and TV devices to further expand the audience of your Android
applications.
Hundreds of stylish and versatile devices — packing hardware features such as GPS, accelerometers,
NFC, and touch screens, combined with reasonably priced data plans — provide an enticing plat-
form upon which to create innovative applications for all Android devices.
Android offers an open alternative for mobile application development. Without artifi cial barriers,
Android developers are free to write applications that take full advantage of increasingly powerful
mobile hardware and distribute them in an open market. As a result, developer interest in Android
devices has exploded as handset sales have continued to grow. As of 2012, there are hundreds of
handset and tablet OEMs, including HTC, Motorola, LG, Samsung, ASUS, and Sony Ericsson.
More than 300 million Android devices have been activated, and that number is growing at a rate of
over 850,000 activations every day.
Using Google Play for distribution, developers can take advantage of an open marketplace, with no
review process, for distributing free and paid applications to all compatible Android devices. Built
on an open-source framework, and featuring powerful SDK libraries, Android has enabled more
than 450,000 applications to be launched in Google Play.
This book is a hands-on guide to building mobile applications using version 4 of the Android SDK.
Chapter by chapter, it takes you through a series of sample projects, each introducing new features
and techniques to get the most out of Android. It covers all the basic functionality to get started, as
well as the information for experienced mobile developers to leverage the unique features of Android
to enhance existing products or create innovative new ones.
Google’s philosophy is to release early and iterate often. Since Android’s fi rst full release in
December 2008, there have been 19 platform and SDK releases. With such a rapid release cycle,
there are likely to be regular changes and improvements to the software and development libraries.
While the Android engineering team works hard to ensure backward compatibility, future releases
are likely to date some of the information provided in this book. Similarly, not all active Android
devices will be running the latest platform release.
Wherever possible, I have included details on which platform releases support the functionality
described, and which alternatives may exist to provide support for users of older devices. Further,
the explanations and examples included will give you the grounding and knowledge needed to write
compelling mobile applications using the current SDK, along with the fl exibility to quickly adapt to
future enhancements.
WHO THIS BOOK IS FOR
This book is for anyone interested in creating applications for the Android platform. It includes
information that will be valuable, whether you’re an experienced mobile developer or making your
fi rst foray, via Android, into writing mobile applications.
It will help if you have used smartphones (particularly phones running Android), but it’s not neces-
sary, nor is prior experience in mobile application development.
It’s expected that you’ll have some experience in software development and be familiar with basic
object-oriented development practices. An understanding of Java syntax is a requirement, and
detailed knowledge and experience is a distinct advantage, though not a strict necessity.
Chapters 1 and 2 introduce mobile development and contain instructions to get you started in
Android. Beyond that, there’s no requirement to read the chapters in order, although a good under-
standing of the core components described in Chapters 3–9 is important before you venture into
the remaining chapters. Chapters 10 and 11 cover important details on how to create an application
that provides a rich and consistent user experience, while Chapters 12–19 cover a variety of optional
and advanced functionality and can be read in whatever order interest or need dictates.
WHAT THIS BOOK COVERS
Chapter 1 introduces Android, including what it is and how it fi ts into existing mobile development.
What Android offers as a development platform and why it’s an exciting opportunity for creating
mobile phone applications are then examined in greater detail.
Chapter 2 covers some best practices for mobile development and explains how to download the
Android SDK and start developing applications. It also introduces the Android Developer Tools and
demonstrates how to create new applications from scratch.
Chapters 3–9 take an in-depth look at the fundamental Android application components. Starting
with examining the pieces that make up an Android application and its lifecycle, you’ll quickly move
on to the application manifest and external resources before learning about “Activities,” their life-
times, and their lifecycles.
You’ll then learn how to create basic user interfaces with layouts, Views, and Fragments, before being
introduced to the Intent and Broadcast Receiver mechanisms used to perform actions and send mes-
sages between application components. Internet resources are then covered, followed by a detailed
look at data storage, retrieval, and sharing. You’ll start with the preference-saving mechanism and
then move on to fi le handling, databases, and Cursors. You’ll also learn how share application data
using Content Providers and access data from the native Content Providers. This section fi nishes with
an examination of how to work in the background using Services and background Threads.
Chapters 10 and 11 build on the UI lessons you learned in Chapter 4, examining how to enhance
the user experience through the use of the Action Bar, Menu System, and Notifi cations. You’ll
learn how to make your applications display-agnostic (optimized for a variety of screen sizes and
resolutions), how to make your applications accessible, and how to use speech recognition within
your applications.
Chapters 12–18 look at more advanced topics. You’ll learn how to use the compass, accelerometers,
and other hardware sensors to let your application react to its environment, and then look at maps
and location-based services. Next, you’ll learn how your applications can interact with users directly
from the home screen using dynamic Widgets, Live Wallpaper, and the Quick Search Box.
After looking at playing and recording multimedia, and using the camera, you’ll be introduced to
Android’s communication capabilities. Bluetooth, NFC, Wi-Fi Direct, and network management
(both Wi-Fi and mobile data connections) are covered, followed by the telephony APIs and the APIs
used to send and receive SMS messages.
Chapter 18 discusses several advanced development topics, including security, IPC, Cloud to Device
Messaging, the License Verifi cation Library, and Strict Mode.
Finally, Chapter 19 examines the options and opportunities available for publishing, distributing,
and monetizing your applications — primarily within Google Play.
HOW THIS BOOK IS STRUCTURED
This book is structured in a logical sequence to help readers of different development backgrounds
learn how to write advanced Android applications. There’s no requirement to read each chapter
sequentially, but several of the sample projects are developed over the course of several chapters,
adding new functionality and other enhancements at each stage.
Experienced mobile developers with a working Android development environment can skim the fi rst
two chapters — which are an introduction to mobile development and instructions for creating your
development environment — and then dive in at Chapters 3–9. These chapters cover the fundamentals
of Android development, so it’s important to have a solid understanding of the concepts they describe.
With this covered, you can move on to the remaining chapters, which look at maps, location-based
services, background applications, and more advanced topics, such as hardware interaction and
networking.
WHAT YOU NEED TO USE THIS BOOK
To use the code samples in this book, you will need to create an Android development environment
by downloading the Android SDK, developer tools, and the Java Development Kit. You may also
want to download and install Eclipse and the Android Developer Tools plug-in to ease your develop-
ment, but neither is a requirement.
Android development is supported in Windows, Mac OS, and Linux, with the SDK available from
the Android web site.
You do not need an Android device to use this book or develop Android applications, though it can
be useful — particularly when testing.
Thứ Ba, 11 tháng 12, 2012
android - cheap 10 -
Expanding the User Experience
WHAT’S IN THIS CHAPTER?
Customizing the Action Bar
Using the Action Bar for application navigation
Using the Android menu system
Choosing Action Bar actions
Creating immersive applications
Creating and displaying Dialogs
Displaying Toasts
Using the Notifi cation Manager to notify users of application events
Creating insistent and ongoing Notifi cations
In Chapter 4, “Building User Interfaces,” you learned how to use Activities, Fragments, lay-
outs, and Views to construct a user interface (UI). To ensure that your UI is stylish, easy to
use, and provides a user experience consistent with the underlying platform and other applica-
tions running in it, this chapter looks at ways to expand the user experience beyond the UI
elements you design.
You’ll start with the Action Bar, introduced in Android 3.0, a system UI component used to
provide a consistent pattern for branding, navigation, and displaying common actions within
your Activities. You’ll learn how to customize the look of the Action Bar, as well as how to use
it to provide navigation with tabs and drop-down lists.
Action Bar actions, application Menus, and Popup Menus use a new approach to menus, opti-
mized for modern touch screen devices. As part of an examination of the Android UI model,
this chapter looks at how to create and use them within your applications. In particular, you’ll learn
how to identify which Menu Items should be displayed as actions on your Action Bar.
Android offers several techniques for applications to communicate with users without an Activity.
You’ll learn how to use Notifi cations and Toasts to alert and update users without interrupting the
active application.
A Toast is a transient, nonmodal dialog-box mechanism used to display information to users with-
out stealing focus from the active application. You’ll learn to display Toasts from any application
component to send unobtrusive on-screen messages to your users.
Whereas a Toast is silent and transient, a Notifi cation represents a more robust mechanism for
alerting users. In many cases, when the user isn’t actively using the mobile phone, it sits silent and
unwatched in a pocket or on a desk until it rings, vibrates, or fl ashes. If a user misses these alerts,
status bar icons are used to indicate that an event has occurred. All these attention-grabbing antics
are available to your Android application through Notifi cations.
You’ll also learn how to customize the appearance and functionality of your Notifi cation when it
appears in the notifi cation tray — providing a mechanism for users to interact with your application
without needing to open it fi rst.
NTRODUCING THE ACTION BAR
The Action Bar component, shown in Figure 10-1, was introduced in Android 3.0 (API level 11). It’s
a navigation panel that replaces the title bar at the top of every Activity and that formalizes a com-
mon Android design pattern.
FIGURE 10-1
It’s possible to hide the Action Bar, but best practice is to keep it and customize it to suit the style
and navigation requirements of your application.
The Action Bar can be added to each Activity within your application and is designed to provide a
consistent UI between applications and within a particular application’s Activities.
The Action Bar provides a consistent framework for providing branding, navigation, and sur-
facing the key actions to be performed within an Activity. Although the Action Bar provides a
framework for presenting this functionality consistently across applications, the following sections
describe how you can select which options are suitable for your application — and how they can be
implemented.
The Action Bar is enabled by default in any Activity that uses the (default) Theme.Holo theme and
whose application has a target (or minimum) SDK version of 11 or higher.
Listing 10-1 shows how to enable the Action Bar by setting the target SDK to Android 4.0.3 (API
level 15) and not modifying the default theme.
<uses-sdk android:targetSdkVersion=”15” />
code snippet PA4AD_Ch10_ ActionBar/AndroidManifest.java
To toggle the visibility of the Action Bar at run time, you can use its show and hide methods:
ActionBar actionBar = getActionBar();
// Hide the Action Bar
actionBar.hide();
// Show the Action Bar
actionBar.show();
Alternatively, you can apply a theme that doesn’t include the Action Bar, such as the Theme.Holo
.NoActionBar theme, as shown in Listing 10-2.
LISTING 10-2: Disabling the Action Bar
<activity
android:name=”.MyNonActionBarActivity”
android:theme=”@android:style/Theme.Holo.NoActionBar”>
code snippet PA4AD_Ch10_ ActionBar/AndroidManifest.java
You can create or customize your own theme that removes the Action Bar by setting the
android:windowActionBar style property to false:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<style name=”NoActionBar” parent=”@style/ActivityTheme”>
<item name=”android:windowActionBar”>false</item>
</style>
</resources>
When you apply a theme that excludes the Action Bar from an Activity, you can’t programmatically
display it at run time. A call to getActionBar will return null.
The Action Bar was introduced in Android 3.0 (API level 11) and is not cur-
rently included in the support library. As a result, you can only use the Action
Bar when running on a host platform with at least Android 3.0. One alternative
is to create a different layout for platforms running pre-Android 3.0. The alter-
native layout would need to implement its own custom Action Bar — typically
in the form of a Fragment — to offer similar functionality.
Customizing the Action Bar
In addition to controlling the implementation of this standard functionality, each application can
modify the appearance of the Action Bar while maintaining the same consistent behavior and gen-
eral layout.
One of the primary purposes of the Action Bar is to provide a consistent UI between applications.
As such, the customization options are purposefully limited, though you can customize the Action
Bar to provide your own application branding and identity.
You can control your branding by specifying the image to appear (if any) at the far left, the application
title to display, and the background Drawable to use. Figure 10-2 shows a customized Action Bar that
uses a logo bitmap to identify the application and a Gradient Drawable as a background image.
FIGURE 10-2
Modifying the Icon and Title Text
By default, the Action Bar displays the Drawable you specify using your application or Activity’s
android:icon attribute, alongside the corresponding android:label attribute on a black background.
You can specify an alternative graphic using the android:logo attribute. Unlike the square icon,
there is no limit to the width of the logo graphic — though it’s good practice to limit it to approxi-
mately double the width of the icon image.
The logo image typically is used to provide the top-level branding for your application, so it’s good
practice to hide the title label when using a logo image. You can do this at run time by setting the
Action Bar’s setDisplayShowTitleEnabled method to false:
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
Where both an icon and logo image are supplied, you can switch between them at run time by using
the setDisplayUseLogoEnabled method:
actionBar.setDisplayUseLogoEnabled(displayLogo);
If you choose to hide the icon and logo, you can do so by setting the setDisplayShowHomeEnabled
method to false:
actionBar.setDisplayShowHomeEnabled(false);
The application icon/logo is typically used as a navigation shortcut to the appli-
cation’s main Activity, so it’s good practice to always have it visible.
You also can use the icon and title text to provide navigation and context cues. Use the setTitle
and setSubTitle methods at run time to modify the text displayed alongside the icon, as demon-
strated in Listing 10-3 and shown in Figure 10-3.
actionBar.setSubtitle(“Inbox”);
actionBar.setTitle(“Label:important”);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarActivity.java
FIGURE 10-3
These text strings can be used to describe the users’ location within the application and the context
within which they’re working. This is particularly useful when using Fragments to change context
rather than the traditional Activity stack. The followings sections provide more details regarding
navigation options.
Customizing the Background
The default background color of the Action Bar depends on the underlying theme. The native
Android Action Bar background is transparent, with the Holo theme background set to black.
You can specify any Drawable as the background image for your Action Bar by using the
setBackgroundDrawable method, as shown in Listing 10-4.
LISTING 10-4: Customizing the Action Bar background
ActionBar actionBar = getActionBar();
Resources r = getResources();
Drawable myDrawable = r.getDrawable(R.drawable.gradient_header);
actionBar.setBackgroundDrawable(myDrawable);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarActivity.java
The Action Bar will scale your image, so it’s best practice to create a scalable Drawable, typically
using either a 9-patch or XML defi ned Drawable. Both alternatives are explored in more detail in
Chapter 11, “Advanced User Experience.”
Under normal circumstances the Action Bar will reserve space at the top of your Activity, with your
layout being infl ated into the remaining space. Alternatively, you can choose to overlay the Action
Bar above your Activity layout by requesting the FEATURE_ACTION_BAR_OVERLAY window feature.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.main);
}
When the overlay mode is enabled, the Action Bar will fl oat above your Activity, potentially obscur-
ing content at the top of your layout.
Enabling the Split Action Bar Mode
The Action Bar was initially introduced in Android 3.0 — a platform release that was focused on
providing the best user experience possible for tablet devices. Android 4.0 (API level 14) sought to
optimize many of the features initially designed for tablets for use on smaller, smartphone devices.
For the Action Bar, this meant the introduction of the split Action Bar. You can enable the split
Action Bar by setting the android:uiOptions attribute within your application or Activity manifest
nodes to splitActionBarWhenNarrow, as shown in Listing 10-5.
LISTING 10-5: Enabling the split Action Bar
<activity
android:label=”My Activity”
android:name=”.ActionBarActivity”
android:logo=”@drawable/ic_launcher”
android:uiOptions=”splitActionBarWhenNarrow”>
code snippet PA4AD_Ch10_ ActionBar/AndroidManifest.xml
On supported devices with narrow screens (such as a smart-
phone in portrait mode), enabling the split Action Bar mode
will allow the system to split the Action Bar into separate sec-
tions. Figure 10-4 shows an example of an Action Bar that has
been laid out with the branding and navigation sections layered
at the top of the screen, with the action sections aligned to the
bottom of the screen.
The layout is calculated and performed by the run time and
may change depending on the orientation of the host device
and any Action Bar confi guration changes you make at run
time.
Customizing the Action Bar to Control
Application Navigation Behavior
The Action Bar introduces a several options for providing
consistent and predictable navigation within your applica-
tion. Broadly speaking, those options can be divided into two
categories:
Application icons — The application icon or logo is used to provide a consistent navigation
path, typically by resetting the application to its home Activity. You can also confi gure the
icon to represent moving “up” one level of context.
FIGURE 10-4
Tabs and drop-downs — The Action Bar supports built-in tabs or drop-down lists that can
be used to replace the visible Fragments within an Activity.
Icon navigation can be considered a way to navigate the Activity stack, whereas tabs and drop-
downs are used for Fragment transitions within an Activity. In practice, the actions you perform
when the application icon is clicked or a tab is changed will depend on the way you’ve implemented
your UI.
Selecting the application icon should change the overall context of your UI in the same way that an
Activity switch might do, whereas changing a tab or selecting a drop-down should change the data
being displayed.
Confi guring Action Bar Icon Navigation Behavior
In most cases, the application icon should act as a shortcut to return to the “home” Activity, typi-
cally the root of your Activity stack. To make the application icon clickable, you must call the
Action Bar’s setHomeButtonEnabled method:
actionBar.setHomeButtonEnabled(true);
Clicking the application icon/logo is broadcast by the system as a special Menu Item click. Menu
Item selections are handled within the onOptionsItemSelected handler of your Activity, with the
ID of the Menu Item parameter set to android.R.id.home, as shown in Listing 10-6.
The process of creating and handling Menu Item selections is described in more detail later in this
chapter.
LISTING 10-6: Handling application icon clicks
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (android.R.id.home) :
Intent intent = new Intent(this, ActionBarActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
code snippet PA4AD_Ch10_ActionBar/src/ActionBarActivity.java
Traditionally, Android applications have started a new Activity to transition between different
contexts. In turn, pressing the back button closes the active Activity and returns to the
previous one.
To supplement this behavior, you can confi gure the application icon to offer “up” navigation.
The back button should always move the user back through contexts (typically in the form of
Activities) that they have already seen, effectively reversing the navigation path they followed to
arrive at the current Activity or screen. This might result in navigation between “siblings” in your
application structure.
In contrast, “up” navigation should always move users to the parent of the current Activity. As a
result, it can move users to a screen they have not previously visited. This is particularly useful for
applications with multiple entry points, allowing users to navigate within an application without
having to return to the application that spawned it.
To enable up navigation for your application icon, call the Action Bar’s setDisplayHomeAsUp-
Enabled method:
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
This has the effect of overlaying an “up” graphic over your application icon, as shown in
Figure 10-5. Note that it’s good practice to use the icon rather than the logo when enabling up
navigation.
FIGURE 10-5
Handling the navigation is left to you to implement. The Action Bar will still trigger the onOptions-
ItemSelected handler with a Menu Item that uses android.R.id.home as its identifi er, as shown
in Listing 10-6.
Such behavior introduces certain risks, particularly if there are multiple ways a user may have navi-
gated to a particular Activity. If in doubt, the up behavior should mirror the back button. In all
cases, the navigation behavior should be predictable.
Using Navigation Tabs
In addition to the application icon navigation, the Action Bar also offers navigation tabs and drop-
down lists. Note that only one of these forms of navigation can be enabled at once. These navigation
options are designed to work closely with Fragments, providing a mechanism for altering the con-
text of the current Activity by replacing the visible Fragments.
Navigation tabs (shown in Figure 10-6) can be considered a replacement for the TabWidget
control.
FIGURE 10-6
To con fi gure your Action Bar to display tabs, call its setNavigationMode method, specifying
ActionBar.NAVIGATION_MODE_TABS. The tabs should provide the application context, so it’s good
practice to disable the title text as well, as shown in Listing 10-7.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarTabActivity.java
Tabs are added to the Action Bar using its addTab method, as shown in Listing 10-8. Start by creat-
ing a new Tab and using its setText and setIcon methods to determine the title and image to be
displayed, respectively. Alternatively, you can use the setCustomView method to replace the stan-
dard text and image layout with your own custom View.
LISTING 10-8: Adding Action Bar navigation tabs
Tab tabOne = actionBar.newTab();
tabOne.setText(“First Tab”)
.setIcon(R.drawable.ic_launcher)
.setContentDescription(“Tab the First”)
.setTabListener(
new TabListener<MyFragment>
(this, R.id.fragmentContainer, MyFragment.class));
actionBar.addTab(tabOne);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarTabActivity.java
Android 4.0 (API level 14) introduced the setContentDescription method,
which allows you include a more detailed content description to better support
accessibility.
The tab switching is handled using a TabListener, allowing you to create Fragment Transactions in
response to tabs being selected, unselected, and reselected, as shown in Listing 10-9. Note that you
are not required to execute the Fragment Transaction created in each handler — the Action Bar will
execute it for you when necessary.
LISTING 10-9: Handling Action Bar tab switching
public static class TabListener<T extends Fragment>
implements ActionBar.TabListener {
private MyFragment fragment;
private Activity activity;
private Class<T> fragmentClass;
continues
private int fragmentContainer;
public TabListener(Activity activity, int fragmentContainer,
Class<T> fragmentClass) {
this.activity = activity;
this.fragmentContainer = fragmentContainer;
this.fragmentClass = fragmentClass;
}
// Called when a new tab has been selected
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (fragment == null) {
String fragmentName = fragmentClass.getName();
fragment =
(MyFragment)Fragment.instantiate(activity, fragmentName);
ft.add(fragmentContainer, fragment, null);
fragment.setFragmentText(tab.getText());
} else {
ft.attach(fragment);
}
}
// Called on the currently selected tab when a different tag is
// selected.
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
ft.detach(fragment);
}
}
// Called when the selected tab is selected.
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO React to a selected tab being selected again.
}
}
code snippet PA4AD_Ch10_ActionBar/src/ActionBarTabActivity.java
The basic workfl ow used within this Tab Listener is to instantiate, confi gure, and then add a new
Fragment to your layout within the onTab-
Selected handler. The Fragment associated with
the unselected tab should be detached from your
layout and recycled if its tab is reselected.
Using Drop-Down Lists for Navigation
You can use an Action Bar drop-down list, as shown
in Figure 10-7, as an alternative to the navigation
tabs or as ideal solutions for applying in-place fi lters
to content being displayed within your Activity.
FIGURE 10-7
LISTING 10-9 (continued)
To con fi gure your Action Bar to display a drop-down list, call its setNavigationMode method,
specifying ActionBar.NAVIGATION_MODE_LIST:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
The drop-down list is implemented much like a Spinner — a view that displays one child at a
time and lets the user pick from among them. Populate the drop-down list by creating a new
Adapter that implements the SpinnerAdapter interface, such as an Array Adapter or Simple
Cursor Adapter:
ArrayList<CharSequence> al = new ArrayList<CharSequence>();
al.add(“Item 1”);
al.add(“Item 2”);
ArrayAdapter<CharSequence> dropDownAdapter =
new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_list_item_1,
al);
To assign the Adapter to your Action Bar, and handle selections, call the Action Bar’s setList-
NavigationCallbacks, passing in your adapter and an OnNavigationListener, as shown in
Listing 10-10.
LISTING 10-10: Creating an Action Bar drop-down list
// Select the drop-down navigation mode.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Create a new Spinner Adapter that contains the values to
// be displayed in the drop down.
ArrayAdapter dropDownAdapter =
ArrayAdapter.createFromResource(this,
R.array.my_dropdown_values,
android.R.layout.simple_list_item_1);
// Assign the callbacks to handle drop-down selections.
actionBar.setListNavigationCallbacks(dropDownAdapter,
new OnNavigationListener() {
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
// TODO Modify your UI based on the position
// of the drop down item selected.
return true;
}
});
code snippet PA4AD_Ch10_ActionBar/src/ActionBarDropDownActivity.java
When a user selects an item from the drop-down list, the onNavigationItemSelected handler will
be triggered. Use the itemPosition and itemId parameters to determine how your UI should be
adapted based on the new selection.
Drop-down list selections typically are used to refi ne existing content, such as to select a particular
account or label within an email client.
Using Custom Navigation Views
For situations where neither tabs nor drop-down lists are appropriate, the Action Bar allows you to
add your own custom View (including layouts) using the setCustomView method:
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.my_custom_navigation);
Custom Views will appear in the same place as the tabs or drop-down lists — to the right of the
application icon but to the left of any actions. To ensure consistency between applications, it’s gener-
ally good form to use the standard navigation modes.
Introducing Action Bar Actions
The right side of the Action Bar is used to display “actions” and the associated overfl ow menu, as
shown in Figure 10-8.
Action Menu
Items
Overflow
Menu
FIGURE 10-8
Action Bar actions and the overfl ow menu were introduced, along with the Action Bar itself, in
Android 3.0 (API level 11) as an alternative to the hardware menu button and its associated options
menu. As such, they are populated using the same APIs that were previously used to create and man-
age the options menu. This process is described in detail later in this chapter.
Actions, then, are Menu Items that are important enough to make them visible and easily available
to users at all times. Action items should be menu options that are either most frequently used, most
important for users to discover, or most expected based on the actions available in similar applica-
tions. Generic and seldom used options, such as settings, help, or “about this app” options, should
never be presented as action items.
Generally speaking, action items should be global actions that don’t depend on the current context.
Navigating within an Activity — for example, changing tabs or selecting an item from a navigation
drop-down — should not alter the available action items.
ADDING AN ACTION BAR TO THE EARTHQUAKE MONITOR
In the following example, the earthquake-monitoring application, whose processing you moved to the
background in Chapter 9, “Working in the Background,” will be enhanced to include an Action Bar.
Chủ Nhật, 9 tháng 12, 2012
book - content
CONTENTS
INTRODUCTION xxxvii
CHAPTER 1: HELLO, ANDROID 1
A Little Background 2
The Not-So-Distant Past 2
Living in the Future 3
What Android Isn’t 3
Android: An Open Platform for Mobile Development 4
Native Android Applications 5
Android SDK Features 6
Access to Hardware, Including Camera, GPS, and Sensors 6
Data Transfers Using Wi-Fi, Bluetooth, and NFC 7
Maps, Geocoding, and Location-Based Services 7
Background Services 7
SQLite Database for Data Storage and Retrieval 8
Shared Data and Inter-Application Communication 8
Using Widgets and Live Wallpaper to Enhance the Home Screen 9
Extensive Media Support and 2D/3D Graphics 9
Cloud to Device Messaging 9
Optimized Memory and Process Management 10
Introducing the Open Handset Alliance 10
What Does Android Run On? 10
Why Develop for Mobile? 11
Why Develop for Android? 11
Factors Driving Android’s Adoption 12
What Android Has That Other Platforms Don’t Have 12
The Changing Mobile Development Landscape 13
Introducing the Development Framework 14
What Comes in the Box 14
Understanding the Android Software Stack 15
The Dalvik Virtual Machine 16
Android Application Architecture 17
Android Libraries 18
CHAPTER 2: GETTING STARTED 19
Developing for Android 20
What You Need to Begin 20
Downloading and Installing the Android SDK 21
Downloading and Installing Updates to the SDK 23
Developing with Eclipse 23
Using the Android Developer Tools Plug-In for Eclipse 24
Using the Support Package 27
Creating Your First Android Application 28
Creating a New Android Project 28
Creating an Android Virtual Device 30
Creating Launch Confi gurations 30
Running and Debugging Your Android Application 33
Understanding Hello World 33
Types of Android Applications 36
Foreground Applications 36
Background Applications 37
Intermittent Applications 37
Widgets and Live Wallpapers 37
Developing for Mobile and Embedded Devices 38
Hardware-Imposed Design Considerations 38
Be Ei cient 38
Expect Limited Capacity 39
Design for Dif erent Screens 39
Expect Low Speeds, High Latency 40
At What Cost? 41
Considering the User’s Environment 42
Developing for Android 43
Being Fast and Ei cient 43
Being Responsive 44
Ensuring Data Freshness 45
Developing Secure Applications 45
Ensuring a Seamless User Experience 46
Providing Accessibility 47
Android Development Tools 47
The Android Virtual Device Manager 48
Android SDK Manager 49
The Android Emulator 50
The Dalvik Debug Monitor Service 50
The Android Debug Bridge 51
The Hierarchy Viewer and Lint Tool 51
Monkey and Monkey Runner 52
CHAPTER 3: CREATING APPLICATIONS AND ACTIVITIES 53
What Makes an Android Application? 54
Introducing the Application Manifest File 55
A Closer Look at the Application Manifest 56
Using the Manifest Editor 63
Externalizing Resources 64
Creating Resources 65
Simple Values 65
Styles and Themes 68
Drawables 68
Layouts 69
Animations 70
Menus 73
Using Resources 74
Using Resources in Code 74
Referencing Resources Within Resources 75
Using System Resources 76
Referring to Styles in the Current Theme 76
Creating Resources for Dif erent Languages and Hardware 77
Runtime Confi guration Changes 79
The Android Application Lifecycle 81
Understanding an Application’s Priority and Its Process’ States 82
Introducing the Android Application Class 83
Extending and Using the Application Class 83
Overriding the Application Lifecycle Events 84
A Closer Look at Android Activities 86
Creating Activities 86
The Activity Lifecycle 87
Activity Stacks 88
Activity States 88
Monitoring State Changes 89
Understanding Activity Lifetimes 91
Android Activity Classes 93
CHAPTER 4: BUILDING USER INTERFACES 95
Fundamental Android UI Design 96
Android User Interface Fundamentals 97
Assigning User Interfaces to Activities 97
Introducing Layouts 98
Defi ning Layouts 99
Using Layouts to Create Device Independent User Interfaces 100
Using a Linear Layout 100
Using a Relative Layout 101
Using a Grid Layout 102
Optimizing Layouts 103
Redundant Layout Containers Are Redundant 103
Avoid Using Excessive Views 105
Using Lint to Analyze Your Layouts 106
To-Do List Example 107
Introducing Fragments 114
Creating New Fragments 115
The Fragment Lifecycle 116
Fragment-Specifi c Lifecycle Events 119
Fragment States 119
Introducing the Fragment Manager 120
Adding Fragments to Activities 120
Using Fragment Transactions 121
Adding, Removing, and Replacing Fragments 122
Using the Fragment Manager to Find Fragments 122
Populating Dynamic Activity Layouts with Fragments 123
Fragments and the Back Stack 124
Animating Fragment Transactions 125
Interfacing Between Fragments and Activities 126
Fragments Without User Interfaces 126
Android Fragment Classes 128
Using Fragments for Your To-Do List 128
The Android Widget Toolbox 132
Creating New Views 133
Modifying Existing Views 133
Customizing Your To-Do List 135
Creating Compound Controls 138
Creating Simple Compound Controls Using Layouts 141
Creating Custom Views 141
Creating a New Visual Interface 142
Handling User Interaction Events 147
Supporting Accessibility in Custom Views 148
Creating a Compass View Example 149
Using Custom Controls 155
Introducing Adapters 156
Introducing Some Native Adapters 156
Customizing the Array Adapter 156
Using Adapters to Bind Data to a View 158
Customizing the To-Do List Array Adapter 158
Using the Simple Cursor Adapter 162
CHAPTER 5: INTENTS AND BROADCAST RECEIVERS 165
Introducing Intents 166
Using Intents to Launch Activities 166
Explicitly Starting New Activities 167
Implicit Intents and Late Runtime Binding 167
Determining If an Intent Will Resolve 168
Returning Results from Activities 169
Native Android Actions 172
Introducing Linkify 174
Native Linkify Link Types 174
Creating Custom Link Strings 175
Using the Match Filter 176
Using the Transform Filter 176
Using Intents to Broadcast Events 177
Broadcasting Events with Intents 177
Listening for Broadcasts with Broadcast Receivers 178
Broadcasting Ordered Intents 180
Broadcasting Sticky Intents 181
Introducing the Local Broadcast Manager 182
Introducing Pending Intents 182
Creating Intent Filters and Broadcast Receivers 183
Using Intent Filters to Service Implicit Intents 183
How Android Resolves Intent Filters 185
Finding and Using Intents Received Within an Activity 186
Passing on Responsibility 187
Selecting a Contact Example 187
Using Intent Filters for Plug-Ins and Extensibility 193
Supplying Anonymous Actions to Applications 193
Discovering New Actions from Third-Party Intent Receivers 194
Incorporating Anonymous Actions as Menu Items 195
Listening for Native Broadcast Intents 196
Monitoring Device State Changes Using Broadcast Intents 197
Listening for Battery Changes 197
Listening for Connectivity Changes 198
Listening for Docking Changes 199
Managing Manifest Receivers at Run Time 199
CHAPTER 6: USING INTERNET RESOURCES 201
Downloading and Parsing Internet Resources 201
Connecting to an Internet Resource 202
Parsing XML Using the XML Pull Parser 203
Creating an Earthquake Viewer 205
Using the Download Manager 210
Downloading Files 211
Customizing Download Manager Notifi cations 213
Specifying a Download Location 213
Cancelling and Removing Downloads 214
Querying the Download Manager 215
Using Internet Services 217
Connecting to Google App Engine 218
Best Practices for Downloading Data Without Draining
the Battery 219
CHAPTER 7: FILES, SAVING STATE, AND PREFERENCES 221
Saving Simple Application Data 222
Creating and Saving Shared Preferences 222
Retrieving Shared Preferences 223
Creating a Settings Activity for the Earthquake Viewer 223
Introducing the Preference Framework and the
Preference Activity 231
Defi ning a Preference Screen Layout in XML 232
Native Preference Controls 234
Using Intents to Import System Preferences into Preference Screens 234
Introducing the Preference Fragment 235
Defi ning the Preference Fragment Hierarchy
Using Preference Headers 235
Introducing the Preference Activity 236
Backward Compatibility and Preference Screens 237
Finding and Using the Shared Preferences Set by Preference Screens 238
Introducing On Shared Preference Change Listeners 238
Creating a Standard Preference Activity for the Earthquake Viewer 238
Persisting the Application Instance State 242
Saving Activity State Using Shared Preferences 242
Saving and Restoring Activity Instance State
Using the Lifecycle Handlers 242
Saving and Restoring Fragment Instance State
Using the Lifecycle Handlers 243
Including Static Files as Resources 245
Working with the File System 246
File-Management Tools 246
Using Application-Specifi c Folders to Store Files 246
Creating Private Application Files 247
Using the Application File Cache 248
Storing Publicly Readable Files 248
CHAPTER 8: DATABASES AND CONTENT PROVIDERS 251
Introducing Android Databases 252
SQLite Databases 252
Content Providers 252
Introducing SQLite 253
Content Values and Cursors 253
Working with SQLite Databases 254
Introducing the SQLiteOpenHelper 255
Opening and Creating Databases Without the SQLite Open Helper 257
Android Database Design Considerations 257
Querying a Database 257
Extracting Values from a Cursor 259
Adding, Updating, and Removing Rows 260
Inserting Rows 260
Updating Rows 261
Deleting Rows 261
Creating Content Providers 262
Registering Content Providers 262
Publishing Your Content Provider’s URI Address 263
Creating the Content Provider’s Database 264
Implementing Content Provider Queries 264
Content Provider Transactions 266
Storing Files in a Content Provider 268
A Skeleton Content Provider Implementation 270
Using Content Providers 274
Introducing the Content Resolver 274
Querying Content Providers 274
Querying for Content Asynchronously Using the Cursor Loader 277
Introducing Loaders 277
Using the Cursor Loader 277
Adding, Deleting, and Updating Content 280
Inserting Content 280
Deleting Content 281
Updating Content 281
Accessing Files Stored in Content Providers 282
Creating a To-Do List Database and Content Provider 283
Adding Search to Your Application 290
Making Your Content Provider Searchable 291
Creating a Search Activity for Your Application 292
Making Your Search Activity the Default Search Provider
for Your Application 293
Performing a Search and Displaying the Results 294
Using the Search View Widget 297
Supporting Search Suggestions from a Content Provider 298
Surfacing Search Results in the Quick Search Box 301
Creating a Searchable Earthquake Content Provider 301
Creating the Content Provider 302
Using the Earthquake Provider 307
Searching the Earthquake Provider 310
Native Android Content Providers 316
Using the Media Store Content Provider 317
Using the Contacts Contract Content Provider 318
Introducing the Contacts Contract Content Provider 318
Reading Contact Details 319
Creating and Picking Contacts Using Intents 323
Modifying and Augmenting Contact Details Directly 324
Using the Calendar Content Provider 325
Querying the Calendar 325
Creating and Editing Calendar Entries Using Intents 327
Modifying Calendar Entries Directly 329
CHAPTER 9: WORKING IN THE BACKGROUND 331
Introducing Services 332
Creating and Controlling Services 332
Creating Services 332
Executing a Service and Controlling Its Restart Behavior 333
Starting and Stopping Services 335
Self-Terminating Services 336
Binding Services to Activities 336
An Earthquake-Monitoring Service Example 338
Creating Foreground Services 343
Using Background Threads 345
Using AsyncTask to Run Asynchronous Tasks 345
Creating New Asynchronous Tasks 346
Running Asynchronous Tasks 347
Introducing the Intent Service 348
Introducing Loaders 349
Manual Thread Creation and GUI Thread Synchronization 349
Using Alarms 351
Creating, Setting, and Canceling Alarms 352
Setting Repeating Alarms 353
Using Repeating Alarms to Schedule Network Refreshes 354
Using the Intent Service to Simplify the Earthquake
Update Service 357
CHAPTER 10: EXPANDING THE USER EXPERIENCE 359
Introducing the Action Bar 360
Customizing the Action Bar 362
Modifying the Icon and Title Text 362
Customizing the Background 363
Enabling the Split Action Bar Mode 364
Customizing the Action Bar to Control Application Navigation Behavior 364
Confi guring Action Bar Icon Navigation Behavior 365
Using Navigation Tabs 366
Using Drop-Down Lists for Navigation 368
Using Custom Navigation Views 370
Introducing Action Bar Actions 370
Adding an Action Bar to the Earthquake Monitor 370
Creating and Using Menus and Action Bar Action Items 377
Introducing the Android Menu System 377
Creating a Menu 379
Specifying Action Bar Actions 380
Menu Item Options 381
Adding Action Views and Action Providers 382
Adding Menu Items from Fragments 383
Defi ning Menu Hierarchies in XML 384
Updating Menu Items Dynamically 385
Handling Menu Selections 386
Introducing Submenus and Context Menus 387
Creating Submenus 387
Using Context Menus and Popup Menus 388
Refreshing the Earthquake Monitor 390
Going Full Screen 392
Introducing Dialogs 394
Creating a Dialog 395
Using the Alert Dialog Class 396
Using Specialized Input Dialogs 397
Managing and Displaying Dialogs Using Dialog Fragments 398
Managing and Displaying Dialogs Using Activity Event Handlers 400
Using Activities as Dialogs 401
Let’s Make a Toast 401
Customizing Toasts 402
Using Toasts in Worker Threads 404
Introducing Notifi cations 405
Introducing the Notifi cation Manager 406
Creating Notifi cations 407
Creating a Notifi cation and Confi guring the Status Bar Display 407
Using the Default Notifi cation Sounds, Lights, and Vibrations 408
Making Sounds 408
Vibrating the Device 409
Flashing the Lights 409
Using the Notifi cation Builder 410
Setting and Customizing the Notifi cation Tray UI 410
Using the Standard Notifi cation UI 411
Creating a Custom Notifi cation UI 412
Customizing the Ticker View 414
Confi guring Ongoing and Insistent Notifi cations 415
Triggering, Updating, and Canceling Notifi cations 416
Adding Notifi cations and Dialogs to the Earthquake Monitor 418
CHAPTER 11: ADVANCED USER EXPERIENCE 425
Designing for Every Screen Size and Density 426
Resolution Independence 426
Using Density-Independent Pixels 426
Resource Qualifi ers for Pixel Density 427
Supporting and Optimizing for Dif erent Screen Sizes 427
Creating Scalable Layouts 428
Optimizing Layouts for Dif erent Screen Types 428
Specifying Supported Screen Sizes 430
Creating Scalable Graphics Assets 431
Color Drawables 431
Shape Drawables 431
Gradient Drawables 432
NinePatch Drawables 434
Creating Optimized, Adaptive, and Dynamic Designs 434
Tes t ing, Tes t ing, Tes t ing 435
Using Emulator Skins 435
Testing for Custom Resolutions and Screen Sizes 435
Ensuring Accessibility 436
Supporting Navigation Without a Touch Screen 436
Providing a Textual Description of Each View 436
Introducing Android Text-to-Speech 437
Using Speech Recognition 439
Using Speech Recognition for Voice Input 440
Using Speech Recognition for Search 441
Controlling Device Vibration 441
Working with Animations 442
Tweened View Animations 442
Creating Tweened View Animations 443
Applying Tweened Animations 443
Using Animation Listeners 444
Animating Layouts and View Groups 444
Creating and Using Frame-by-Frame Animations 445
Interpolated Property Animations 446
Creating Property Animations 447
Creating Property Animation Sets 449
Using Animation Listeners 449
Enhancing Your Views 450
Advanced Canvas Drawing 450
What Can You Draw? 450
Getting the Most from Your Paint 451
Improving Paint Quality with Anti-Aliasing 456
Canvas Drawing Best Practice 457
Advanced Compass Face Example 458
Hardware Acceleration 466
Managing Hardware Acceleration Use in Your Applications 466
Checking If Hardware Acceleration Is Enabled 467
Introducing the Surface View 467
When to Use a Surface View 467
Creating Surface Views 468
Creating 3D Views with a Surface View 470
Creating Interactive Controls 470
Using the Touch Screen 471
Using the Device Keys, Buttons, and D-Pad 475
Using the On Key Listener 475
Using the Trackball 476
Advanced Drawable Resources 476
Composite Drawables 476
Transformative Drawables 476
Layer Drawables 477
State List Drawables 478
Level List Drawables 479
Copy, Paste, and the Clipboard 479
Copying Data to the Clipboard 479
Pasting Clipboard Data 480
CHAPTER 12: HARDWARE SENSORS 481
Using Sensors and the Sensor Manager 482
Supported Android Sensors 482
Introducing Virtual Sensors 483
Finding Sensors 484
Monitoring Sensors 485
Interpreting Sensor Values 487
Monitoring a Device’s Movement and Orientation 489
Determining the Natural Orientation of a Device 490
Introducing Accelerometers 491
Detecting Acceleration Changes 492
Creating a Gravitational Force Meter 494
Determining a Device’s Orientation 497
Understanding the Standard Reference Frame 497
Calculating Orientation Using the Accelerometer and
Magnetic Field Sensors 498
Remapping the Orientation Reference Frame 500
Determining Orientation Using the Deprecated Orientation Sensor 501
Creating a Compass and Artifi cial Horizon 502
Introducing the Gyroscope Sensor 505
Introducing the Environmental Sensors 506
Using the Barometer Sensor 506
Creating a Weather Station 508
CHAPTER 13: MAPS, GEOCODING, AND
LOCATION-BASED SERVICES 513
Using Location-Based Services 514
Using the Emulator with Location-Based Services 515
Updating Locations in Emulator Location Providers 515
Confi guring the Emulator to Test Location-Based Services 516
Selecting a Location Provider 516
Finding Location Providers 517
Finding Location Providers by Specifying Criteria 517
Determining Location Provider Capabilities 518
Finding Your Current Location 519
Location Privacy 519
Finding the Last Known Location 519
Where Am I Example 519
Refreshing the Current Location 522
Tracking Your Location in Where Am I 525
Requesting a Single Location Update 527
Best Practice for Location Updates 527
Monitoring Location Provider Status and Availability 528
Using Proximity Alerts 530
Using the Geocoder 532
Reverse Geocoding 533
Forward Geocoding 534
Geocoding Where Am I 535
Creating Map-Based Activities 536
Introducing Map View and Map Activity 537
Getting Your Maps API Key 537
Getting Your Development/Debugging MD5 Fingerprint 537
Getting your Production/Release MD5 Fingerprint 538
Creating a Map-Based Activity 538
Maps and Fragments 540
Confi guring and Using Map Views 541
Using the Map Controller 541
Mapping Where Am I 542
Creating and Using Overlays 546
Creating New Overlays 546
Introducing Projections 547
Drawing on the Overlay Canvas 547
Handling Map Tap Events 548
Adding and Removing Overlays 549
Annotating Where Am I 549
Introducing My Location Overlay 553
Introducing Itemized Overlays and Overlay Items 554
Pinning Views to the Map and Map Positions 556
Mapping Earthquakes Example 558
CHAPTER 14: INVADING THE HOME SCREEN 565
Introducing Home Screen Widgets 566
Creating App Widgets 567
Creating the Widget XML Layout Resource 567
Widget Design Guidelines 567
Supported Widget Views and Layouts 568
Defi ning Your Widget Settings 569
Creating Your Widget Intent Receiver and Adding It to the
Application Manifest 570
Introducing the App Widget Manager and Remote Views 572
Creating and Manipulating Remote Views 572
Applying Remote Views to Running App Widgets 574
Using Remote Views to Add Widget Interactivity 575
Refreshing Your Widgets 577
Using the Minimum Update Rate 577
Using Intents 578
Using Alarms 579
Creating and Using a Widget Confi guration Activity 580
Creating an Earthquake Widget 582
Introducing Collection View Widgets 587
Creating Collection View Widget Layouts 589
Creating the Remote Views Service 591
Creating a Remote Views Factory 591
Populating Collection View Widgets Using a Remote Views Service 594
Adding Interactivity to the Items Within a Collection View Widget 595
Binding Collection View Widgets to Content Providers 596
Refreshing Your Collection View Widgets 598
Creating an Earthquake Collection View Widget 598
Introducing Live Folders 605
Creating Live Folders 606
The Live Folder Content Provider 606
The Live Folder Activity 608
Creating an Earthquake Live Folder 610
Surfacing Application Search Results Using the Quick Search Box 614
Surfacing Search Results to the Quick Search Box 614
Adding the Earthquake Example Search Results to the
Quick Search Box 615
Creating Live Wallpaper 616
Creating a Live Wallpaper Defi nition Resource 616
Creating a Wallpaper Service 617
Creating a Wallpaper Service Engine 618
CHAPTER 15: AUDIO, VIDEO, AND USING THE CAMERA 621
Playing Audio and Video 622
Introducing the Media Player 623
Preparing Audio for Playback 624
Initializing Audio Content for Playback 624
Preparing Video for Playback 625
Playing Video Using the Video View 625
Creating a Surface for Video Playback 626
Controlling Media Player Playback 629
Managing Media Playback Output 631
Responding to the Volume Controls 631
Responding to the Media Playback Controls 632
Requesting and Managing Audio Focus 635
Pausing Playback When the Output Changes 637
Introducing the Remote Control Client 637
Manipulating Raw Audio 640
Recording Sound with Audio Record 640
Playing Sound with Audio Track 642
Creating a Sound Pool 643
Using Audio Ef ects 645
Using the Camera for Taking Pictures 646
Using Intents to Take Pictures 646
Controlling the Camera Directly 648
Camera Properties 648
Camera Settings and Image Parameters 649
Controlling Auto Focus, Focus Areas, and Metering Areas 650
Using the Camera Preview 651
Detecting Faces and Facial Features 653
Taking a Picture 654
Reading and Writing JPEG EXIF Image Details 655
Recording Video 656
Using Intents to Record Video 656
Using the Media Recorder to Record Video 657
Confi guring the Video Recorder 658
Previewing the Video Stream 660
Controlling the Recording 660
Creating a Time-Lapse Video 661
Using Media Ef ects 661
Adding Media to the Media Store 662
Inserting Media Using the Media Scanner 662
Inserting Media Manually 663
CHAPTER 16: BLUETOOTH, NFC, NETWORKS, AND WI-FI 665
Using Bluetooth 666
Managing the Local Bluetooth Device Adapter 666
Being Discoverable and Remote Device Discovery 669
Managing Device Discoverability 669
Discovering Remote Devices 671
Bluetooth Communications 673
Opening a Bluetooth Server Socket Listener 674
Selecting Remote Bluetooth Devices for Communications 675
Opening a Client Bluetooth Socket Connection 676
Transmitting Data Using Bluetooth Sockets 677
Managing Network and Internet Connectivity 679
Introducing the Connectivity Manager 679
Supporting User Preferences for Background Data Transfers 679
Finding and Monitoring Network Connectivity 681
Managing Wi-Fi 682
Monitoring Wi-Fi Connectivity 683
Monitoring Active Wi-Fi Connection Details 684
Scanning for Hotspots 684
Managing Wi-Fi Confi gurations 685
Creating Wi-Fi Network Confi gurations 685
Transferring Data Using Wi-Fi Direct 686
Initializing the Wi-Fi Direct Framework 686
Enabling Wi-Fi Direct and Monitoring Its Status 688
Discovering Peers 689
Connecting with Peers 690
Transferring Data Between Peers 692
Near Field Communication 693
Reading NFC Tags 693
Using the Foreground Dispatch System 695
Introducing Android Beam 697
Creating Android Beam Messages 697
Assigning the Android Beam Payload 699
Receiving Android Beam Messages 699
CHAPTER 17: TELEPHONY AND SMS 701
Hardware Support for Telephony 701
Marking Telephony as a Required Hardware Feature 702
Checking for Telephony Hardware 702
Using Telephony 702
Initiating Phone Calls 703
Replacing the Native Dialer 703
Accessing Telephony Properties and Phone State 705
Reading Phone Device Details 705
Reading Network Details 706
Reading SIM Details 707
Reading Data Connection and Transfer State Details 707
Monitoring Changes in Phone State Using the Phone State Listener 708
Monitoring Incoming Phone Calls 709
Tracking Cell Location Changes 710
Tracking Service Changes 710
Monitoring Data Connectivity and Data Transfer Status Changes 711
Using Intent Receivers to Monitor Incoming Phone Calls 712
Introducing SMS and MMS 713
Using SMS and MMS in Your Application 713
Sending SMS and MMS from Your Application Using Intents 713
Sending SMS Messages Using the SMS Manager 714
Sending Text Messages 715
Tracking and Confi rming SMS Message Delivery 715
Conforming to the Maximum SMS Message Size 717
Sending Data Messages 717
Listening for Incoming SMS Messages 717
Simulating Incoming SMS Messages in the Emulator 719
Handling Data SMS Messages 719
Emergency Responder SMS Example 720
Automating the Emergency Responder 729
Introducing SIP and VOIP 737
CHAPTER 18: ADVANCED ANDROID DEVELOPMENT 739
Paranoid Android 740
Linux Kernel Security 740
Introducing Permissions 740
Declaring and Enforcing Permissions 741
Enforcing Permissions when Broadcasting Intents 742
Introducing Cloud to Device Messaging 743
C2DM Restrictions 743
Signing Up to Use C2DM 744
Registering Devices with a C2DM Server 744
Sending C2DM Messages to Devices 748
Receiving C2DM Messages 749
Implementing Copy Protection Using the License
Verifi cation Library 750
Installing the License Verifi cation Library 750
Finding Your License Verifi cation Public Key 751
Confi guring Your License Validation Policy 751
Performing License Validation Checks 752
Introducing In-App Billing 753
In-App Billing Restrictions 754
Installing the In-App Billing Library 754
Finding Your Public Key and Defi ning Your Purchasable Items 754
Initiating In-App Billing Transactions 755
Handling In-App Billing Purchase Request Responses 756
Using Wake Locks 757
Using AIDL to Support Inter-Process Communication for Services 759
Implementing an AIDL Interface 759
Making Classes Parcelable 759
Creating an AIDL Service Defi nition 762
Implementing and Exposing the AIDL Service Defi nition 762
Dealing with Dif erent Hardware and Software Availability 765
Specifying Hardware as Required 766
Confi rming Hardware Availability 766
Building Backward-Compatible Applications 766
Parallel Activities 767
Interfaces and Fragments 768
Optimizing UI Performance with Strict Mode 769
CHAPTER 19: MONETIZING, PROMOTING, AND DISTRIBUTING
APPLICATIONS 771
Signing and Publishing Applications 772
Signing Applications Using the Export Android Application Wizard 772
Distributing Applications 774
Introducing the Google Play 774
Getting Started with Google Play 775
Publishing Applications 776
Application Reports Within the Developer Console 778
Accessing Application Error Reports 778
An Introduction to Monetizing Your Applications 779
Application Marketing, Promotion, and Distribution Strategies 780
Application Launch Strategies 781
Promotion Within Google Play 781
Internationalization 782
Analytics and Referral Tracking 783
Using Google Analytics for Mobile Applications 784
Referral Tracking with Google Analytics 786
INDEX 787
Thứ Năm, 6 tháng 12, 2012
Android thanks
ACKNOWLEDGMENTS
FIRST, I’D LIKE TO THANK KRISTY, whose love, patience, and understanding are pushed to new limits
every time I forget what’s involved in writing a book and agree to do another one. Your support
makes everything I do possible.
A big thank you to my friends and colleagues at Google, particularly the Android engineers and my
colleagues in developer relations. The pace at which Android grows makes life diffi cult for those of
us who choose to write books, but the opportunities it creates for developers makes the stress and
rewrites easy to bear.
I also thank Dan Ulery for his sharp eye and valuable insights; Robert Elliot and John Sleeva for
their patience in waiting for me to get this book fi nished; San Dee Phillips; and the whole team at
Wrox for helping to get it done.
A special shout-out goes out to the entire Android developer community. Your passion, hard work,
and excellent applications have helped make Android the huge success that it is. Thank you.
Thứ Ba, 4 tháng 12, 2012
ID
APP Driver:
private final int SITE_ID = 3384;
private final String SITE_KEY = "5b624acc05cd84ef264b3c142f8c7fee";
private final int MEDIA_ID = 862;
private final int SITE_ID = 3384;
private final String SITE_KEY = "5b624acc05cd84ef264b3c142f8c7fee";
private final int MEDIA_ID = 862;
Chủ Nhật, 2 tháng 12, 2012
Original English - 23 - Drag
Original English - 23 - Drag
HIGH PRICE OF MOM'S HELP IS DRAG ON FAMILY BUSINESS
DEAR ABBY:
Twenty years ago, my sister and I bought a business from our mother. We all love and respect one
another and get along well. We will be finished paying off the business in two years.
Our problem: Mom, who is now 77, still draws a salary from us above and beyond the payment for
the business. Her workload has lessened greatly, as it should. She could do all of her work in one
day and lessen the burden of her salary. However, she says she'd "go crazy" if she retired. We
don't want that. She could still come in as often as she wants and do her personal paperwork, bank-
ing, letter-writing, reading, etc. These are all things she does at "work" -- on the clock.
If we try to discuss this, Mom gets hurt and says, "Just let me know when I'm not worth the money."
We don't want to do that. We would hope she would see the fairness of this and suggest it herself.
Business expenses are going through the roof, and there are updates we should make, but we
can't do it as long as we are paying Mom at the level we are, on top of the money for the buy-out.
-- DAUGHTERS DEAREST
HIGH PRICE OF MOM'S HELP IS DRAG ON FAMILY BUSINESS
DEAR ABBY:
Twenty years ago, my sister and I bought a business from our mother. We all love and respect one
another and get along well. We will be finished paying off the business in two years.
Our problem: Mom, who is now 77, still draws a salary from us above and beyond the payment for
the business. Her workload has lessened greatly, as it should. She could do all of her work in one
day and lessen the burden of her salary. However, she says she'd "go crazy" if she retired. We
don't want that. She could still come in as often as she wants and do her personal paperwork, bank-
ing, letter-writing, reading, etc. These are all things she does at "work" -- on the clock.
If we try to discuss this, Mom gets hurt and says, "Just let me know when I'm not worth the money."
We don't want to do that. We would hope she would see the fairness of this and suggest it herself.
Business expenses are going through the roof, and there are updates we should make, but we
can't do it as long as we are paying Mom at the level we are, on top of the money for the buy-out.
-- DAUGHTERS DEAREST
Thứ Ba, 20 tháng 11, 2012
Effortless English - change
Effortless English - change
NO AFFECTION ANYMORE
DEAR ABBY:
My husband of 39 years no longer hugsme or shows me any affection. I have seen him through
cancer and diabetes. We have four grown children, and we have been seeinga therapist for a year
and a half. He is kind, generous and friendly, but there are no complimentsor any of the flirtatious
banterwe used to enjoy.
He swears he's not having an affair, and he doesn't know why he has changed. Perhaps you do?
-- GRACE IN PHOENIX
Changed
Thứ Năm, 15 tháng 11, 2012
1. Introduction
To integrate our SDK as a publisher for Metaps, there are multiple ways to both display and
receive confirmation for Offers on the ad network. Before implementation, please consider
which method you will use to integrate, and choose the method that best matches your app.
How to use the Metaps Offerwall
The method available to display Offers depends on the type of app, as illustrated in the
diagram below.
How to receive Reward Confirmation
There are two ways to be notified of confirmation that the end-user can receive their reward
and publisher is entitled to a reward payout (Reward Confirmation). You can choose to
receive the confirmation from within the app, or have a notification sent to the server of your
choosing.
The meanings of the values above are as follows:
net.metaps.sdk.CLIENT_ID: Metaps ID
An unique identification assigned to advertisers and media. This can be confirmed at the
Login screen.
net.metaps.sdk.APP_ID: App ID
An unique identification assigned by metaps to each registered app. This can be
confirmed at the Login screen.
net.metaps.sdk.APP_KEY: Authentication key
An unique identification assigned by metaps for authentication purposes. This can
be confirmed at the Login screen.
net.metaps.sdk.PROMOTION_ID: Promotion ID
A string (up to 16 characters) that can be used for identifying your promotion
campaign.
net.metaps.sdk.MARKET: Market
A string (up to 16 character) that can be used to identify your intended market.
net.metaps.sdk.MODE: Test/Release Indication
1=Test/Debug, 0=Release
Add Resource Files to Project
Inside the downloaded SDK zip file, there is a folder named "res". This folder contains the
layout files necessary for your project to display the Offerwall correctly. Copy all these files
into your project, taking care not to overwrite any existing resources that you may have
already created, such as strings.xml.
If you already have an existing strings.xml, you should append the string resources
required by the SDK to your existing strings.xml.
Each file in the “res” folder is explained below. You can freely customize the design of the
layouts by editing or replacing files, as long as the names of the files/layouts remain the
same.
To ensure these layouts work properly, a specified ID must be used. Details regarding
these IDs are explained later in this documentation. If any of the IDs are missing, your app
may not work properly, so please pay close attention when customizing.
Important: Be careful not to overwrite your existing strings.xml, or forget to
append the Metaps SDK strings to your existing file.
It is possible to overwrite the “app_name” value as set in strings.xml to whatever
you want or use.
If you require other languages than English / Japanese / Chinese, it is possible to
create respective resource folders to support that language. If creating these folders,
please adhere to the Android standard naming conventions.
Settings for the Publisher
It is necessary to fill in the following publisher app settings from the Metaps dashboard.
After you login to the dashboard, select “Developer” “Monetize” then click on the “Edit”
button under “Reward Edit” for the registered app.
The fields that can be edited are listed below.
Title This string is shown at the top of the Offerwall. You can
set this as your app name or whatever you wish.
User-reward Unit in your App The virtual currency unit that you use inside the app.
User-reward Amount The conversion rate used to reward users points. You
will need to put in a value for the amount of virtual currency
to reward for every 100 points received from an offer.
e.g. if you input “20” here and your virtual currency unit is
“stars”, if you receive 100 points from the offer, the user
will receive 20 stars.
Reward Confirmation Metaps Server: Select this if you will receive Reward
Confirmation inside the app.
Notify Your Server: Select this is if Reward Confirmation
is to be sent to your server first.
Use SDK Decline fulfillment notification via the use of html tag
or SDK: Unused option.
Will notify Metaps of fulfillment via the use of html tag
or SDK: Please select this option.
Reward Confirmation URL If you have selected “Notify Your Server” in the Reward
Confirmation setting above, you will need to input your
server URL here to be notified of Reward Confirmation.
5. Displaying Offers with the SDK
Initialize the SDK Inside your Project
Note: This section on initialization is not required for developers using WebView, and
can skip to the next section on “Displaying Offers Using WebView"
Before using the SDK to display the Offerwall, you must first call the static method
startReward of the MetapsFactory class.
It is essential that the startReward method be called before any other processes are
executed. Therefore it is recommended that you call startReward in your Activity’s
onResume method.
About “Receiver”
The "Receiver" that appears in the sample code above assumes that you will implement the
net.Metaps.sdk.Receiver interface as "MyReceiver" (or whatever class name you want).
Inside "MyReceiver", you will need to create the Java code that processes the received
points from Metaps, and give virtual currency or unlock rewards for the end-user.14
For further details, look at the section, "Receiving Reward Confirmation" under the chapter
"Receiving Reward Confirmation in Your App".
About the parameters for the startReward method
Inside the SDK zip file you will find a JavaDoc under the “doc” folder. For more details on
the parameters, please refer to the JavaDoc.
About “end-user ID”
For the end-user ID, please pass a unique ASCII string, no longer than 32 characters in
length to identify each end-user in your application. If the notification for Reward
Confirmation is to be sent to your server, it is required to pass this end-user ID string at
some point. (i.e. at initialization or before displaying the Offerwall)
It is possible to perform initialization while passing an empty string or null value, but be sure
to pass a valid value by the time your display the Offerwall.
About “scenario”
The scenario string is an ASCII string with a maximum length of 64 characters. Depending
on your app’s calling activity, this can be used to branch out the process for receiving
Reward Confirmation.
It is possible to perform initialization while passing an empty string or null value at this point.
Displaying the Offerwall from a Native App
The ways in which to show Reward Ads are highly customizable, and can be tailored to
meet the needs of your app. Although the Offerwall can be called in different ways, the
sample code below illustrates one of the simpler ways this can be done.
Thứ Năm, 8 tháng 11, 2012
Working with Animations
In Chapter 3, you learned how to define animations as external resources. Now, you get the opportunity
to put them to use.
Android offers two kinds of animation:
➤ Frame-by-Frame Animations Traditional cell-based animations in which a different Draw-
able is displayed in each frame. Frame-by-frame animations are displayed within a View,
using its Canvas as a projection screen.
➤ Tweened Animations Tweened animations are applied to Views, letting you define a series
of changes in position, size, rotation, and opacity that animate the View contents.
Both animation types are restricted t o the original bounds of the View they’re
applied to. Rotations, translations, and sc aling transformations that extend beyond
the original boundaries of the View will result in the contents being clipped.
Introducing Tweened Animations
Tweened animations offer a simple way to provide depth, movement, or feedback to your users at a
minimal resource cost.
Using animations to apply a set of orientation, scale, position, and opacity changes is much less
resource-intensive than manually redrawing the Canvas to achieve similar effects, not to mention far
simpler to implement.
Tweened animations are commonly used to:
➤ Transition between Activities.
➤ Transition between layouts within an Activity.
➤ Transition between different content displayed within the same View.
➤ Provide user feedback such as:
➤ Indicating progress.
➤ ‘‘Shaking’’ an input box to indicate an incorrect or invalid data entry.
Creating Tweened Animations
Tweened animations are created using theAnimation class. The following list explains the animation
types available.
➤ AlphaAnimation Lets you animate a change in the View’s transparency (opacity or alpha
blending).
➤ RotateAnimation Lets you spin the selected View canvas in the XY plane.
➤ ScaleAnimation Allows you to zoom in to or out from the selected View.
➤ TranslateAnimation Lets you move the selected View around the screen (although it will
only be drawn within its original bounds).
Android offers the AnimationSetclass to group and configure animations to be run as a set. You can
define the start time and duration of each animation used within a set to control the timing and order
of the animation sequence.
It’s important to set the start offset and duration for each child animation, or they
will all start and complete at the same time.
Listings 15-12 and 15-13 demonstrate how to create the same animation sequence in code or as an
external resource.
LISTING 15-12: Creating a tweened animation in code
>>>>>>>>>>>>>>>>code
As you can see, it’s generally both easier and more intuitive to create your animation sequences using
an external animation resource.
Applying Tweened Animations
Animations can be applied to any View by calling its startAnimation method and passing in the Ani-
mation or Animation Set to apply.
Animation sequences will run once and then stop, unless you modify this behavior using the
setRepeatMode and setRepeatCount methods on the Animation or Animation Set. You can force an
animation to loop or repeat in reverse by setting the repeat mode of RESTARTor REVERSErespectively.
Setting the repeat count controls the number of times the animation will repeat.
Listing 15-14 shows an Animation that repeats indefinitely.
LISTING 15-14: Applying an Animation that loops continuously
myAnimation.setRepeatMode( Animation.RESTART);
myAnimation.setRepeatCount(Animation.INFINITE );
myView.startAnimation(myAnimation);
Using Animation Listeners
The AnimationListenerlets you create an event handler that’s fired when an animation begins or ends.
This lets you perform actions before or after an animation has completed, such as changing the View
contents or chaining multiple animations.
Call setAnimationListeneron an Animation object, and pass in a new implementation of
AnimationListener, overriding onAnimationEnd, onAnimationStart ,andonAnimationRepeat as
required.
Listing 15-15 shows the basic implementation of an Animation Listener.
>>>>>>>>>>>>>>>>>code
Animating Layouts and View Groups
A LayoutAnimationis used to animate View Groups, applying a single Animation (or Animation Set)
to each child View in a predetermined sequence.
Use aLayoutAnimationControllerto specify an Animation (or Animation Set) that’s applied to each
child View in a View Group. Each View it contains will have the same animation applied, but you can
use the Layout Animation Controller to specify the order and start time for each View.
Android includes twoLayoutAnimationControllerclasses.
➤ LayoutAnimationController Lets you select the start offset of each View (in milliseconds)
and the order (forward, reverse,andrandom ) to apply the animation to each child View.
➤ GridLayoutAnimationController Is a derived class that lets you assign the animation
sequence of the child Views using grid row and column references.
Creating Layout Animations
To create a new Layout Animation, start by defining the Animation to apply to each child View. Then
create a new LayoutAnimation, either in code or as an external animation resource, that references the
animation to apply and defines the order and timing in which to apply it.
Listing 15-16 show the definition of a simple Animation stored as popin.xml in the res/anim folder, and
a Layout Animation definition stored as popinlayout.xml.
The Layout Animation applies a simple ‘‘pop-in’’ animation randomly to each child View of any View
Group it’s assigned to.
>>>>>>>>>>>>>>>>>code
Using Layout Animations
Once you’ve defined a Layout Animation, you can apply it to a View Group either in code or in the
layout XML resource. In XML this is done using the android:layoutAnimation tag in the layout
definition:
android:layoutAnimation="@anim/popinlayout"
To set a Layout Animation in code, call setLayoutAnimation on the View Group, passing in a reference
to the LayoutAnimationobject you want to apply.
In each case, the Layout Animation will execute once, when the View Group is first laid out. You can
force it to execute again by calling scheduleLayoutAnimation on the ViewGroup object. The animation
will then be executed the next time the View Group is laid out.
Layout Animations also support Animation Listeners.
>>>>>>>>>>>>>>>code
Creating and Using Frame-by-Frame Animations
Frame-by-frame animations are akin to traditional cel-based cartoons in which an image is chosen for
each frame. Where tweened animations use the ta rget View to supply the content of the animation,
frame-by-frame animations let you specify a series of Drawable objects that are used as the background
to a View.
The AnimationDrawable class is used to create a new frame-by-frame animation presented as a
Drawable resource. You can define your Animation Drawa ble resource as an external resource in your
project’s res/drawable folder using XML.
Use the<animation-list>tagtogroupacollectionof <item>nodes, each of which uses a drawable
attribute to define an image to display, and a duration attribute to specify the time (in milliseconds) to
display it.
Listing 15-18 shows how to create a simple animation that displays a rocket taking off (rocket images
not included). The file is stored as res/drawable/animated_rocket.xml.
>>>>>>>>>>>>>Code
To display your animation, set it as the background to a View using the setBackgroundResource
method.
ImageView image = (ImageView)findViewById(R.id.my_animation_frame);
image.setBackgroundResource(R.drawable.animated_rocket);
Alternatively, use thesetBackgroundDrawable to use a Drawable instance instead of a resource refer-
ence. Run the animation calling its startmethod.
Thứ Tư, 7 tháng 11, 2012
14 Sensors
Sensors
WHAT’S IN THIS CHAPTER?
➤ Using the Sensor Manager
➤ The available sensor-types
➤ Monitoring sensors and interpreting sensor values
➤ Using the compass, accelerometer, and orientation sensors
➤ Remapping your orientation reference frame
➤ Controlling device vibration
Modern mobile phones are much more than simple communications devices with a connection
to the Internet. With microphones, cameras, accel erometers, compasses, temperature gauges,
and brightness detectors, smartphones have becomeextra-sensory devices, able to augment your
own perceptions.
Later chapters will explore use of the camera and microphone; in this chapter you will explore
the environmental sensors potentially available on Android devices.
Sensors that detect physical and environmental properties offer an exciting innovation for
enhancing the user experience of mobile applications. The incorporation of electronic com-
passes, gravity sensors, brightness gauges, and proximity sensors in modern devices provides an
array of new possibilities for interacting with devices, such as augmented reality and physical
movement-based input.
In this chapter you’ll be introduced to the sensors available in Android and how to use the Sen-
sor Manager to monitor them. You’ll take a closer look at the accelerometer and orientation
sensors and use them to determine changes in the device orientation and acceleration. This is
particularly useful for creating motion-based u ser interfaces, letting you add new dimensions to
your location-based applications.
You’ll also learn how to control device vibration to use force feedback in your applications.
USING SENSORS AND THE SENSOR MANAGER
The Sensor Manager is used to manage the sensor hardware available on Android devices. Use
getSystemService to return a reference to the Sensor Manager Service, as shown in the following
snippet:
String service_name = Context.SENSOR_SERVICE;
SensorManager sensorManager = (SensorManager)getSystemService(service_name);
Introducing Sensors
Like location-based Services, Android abstracts the sensor implementations of each device. The Sensor
class is used to describe the properties of each hardw are sensor, including its type, name, manufacturer,
and details on its accuracy and range.
The Sensor class includes a set of constants used to describe what type of hardware sensor is being
represented by a Sensor object. These constants take the form of Sensor.TYPE_<TYPE> . The follow-
ing section describes each supported sensor-type , after which you’ll learn how to find and use those
sensors.
Supported Android Sensors
The following is a list of the sensor-types currently available; note that the hardware on the host device
determines which of these sensors are actually available to your application.
➤ Sensor.TYPE_ACCELEROMETER A three-axis accelerometer sensor that returns the current
acceleration along three axes in m/s
2
. The accelerometer is explored in greater detail later
in this chapter.
➤ Sensor.TYPE_GYROSCOPE A gyroscopic sensor that returns the current device orientation on
three axes in degrees.
➤ Sensor.TYPE_LIGHT An ambient light sensor that returns a single value describing the ambi-
ent illumination in lux. A light sensor is commonly used to dynamically control the screen
brightness.
➤ Sensor.TYPE_MAGNETIC_FIELD A magnetic field sensor that finds the current magnetic field
in microteslas along three axes.
➤ Sensor.TYPE_ORIENTATION An orientation sensor that returns the device orientation on
three axes in degrees. The orientation sensor is explored in greater detail later in this chapter.
➤ Sensor.TYPE_PRESSURE A pressure sensor that returns a single value, the current pressure
exerted on the device in kilopascals.
➤ Sensor.TYPE_PROXIMITY A proximity sensor that indicates the distance between the device
and the target object in meters. How a target object is selected, and the distances supported,
will depend on the hardware implementation of the proximity detector. A typical use for the
proximity sensor is to detect when the device is being held up against the user’s ear and to
automatically adjust screen brightness or initiate a voice command.
Finding Sensors
An Android device can include multiple implementati ons of a particular sensor-type. To find the default
Sensor implementation for a particular type use the Sensor Manager’s getDefaultSensor method,
passing in the sensor-type required from the constants described in the previous section.
The following snippet returns the default gyroscope. If no default Sensor exists for the given type, the
method returns null.
Sensor defaultGyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
Alternatively, use getSensorList to return a list of all the available Sensors of a given type, as shown
in the following code, which returns all the available pressure sensor objects:
List<Sensor> pressureSensors = sensorManager.getSensorList(Sensor.TYPE_PRESSURE);
To find every Sensor available on the host platform use getSensorList , passing in Sensor.TYPE_ALL,
as shown here:
List<Sensor> allSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
This technique lets you determine which Sensors, and sensor-types, are available on the host platform.
Using Sensors
Listing 14-1 shows the standard pattern for monitoring hardware sensor results. Later sections will
take a closer look at orientation and acceleration Sensor implementations in particular.
Implement a SensorEventListener.Usethe onSensorChangedmethod to monitor Sensor values and
onAccuracyChangedto react to changes in a Sensor’s accuracy.
LISTING 14-1:Sensor Event Listener skeleton code
final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent sensorEvent) {
// TODO Monitor Sensor changes.
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO React to a change in Sensor accuracy.
}
};
The SensorEvent parameter in theonSensorChangedmethod includes four properties used to describe
aSensorevent:
➤ sensor The Sensor object that triggered the event.
➤ accuracy The accuracy of the Sensor when the event occurred (low, medium, high, or unre-
liable, as described in the next list).
➤ values A float array that contains the new value(s) detected. The next section explains the
values returned for each sensor-type.
➤ timestamp The time (in nanoseconds) at which the Sensor event occurred.
You can monitor changes in the accuracy of a Sensor separately, using the onAccuracyChangedmethod.
In both handlers the accuracy value represents feedback from the monitored Sensor’s accuracy, using
one of the following constants:
➤ SensorManager.SENSOR_STATUS_ACCURACY_LOW Indicates that the Sensor is reporting with
low accuracy and needs to be calibrated
➤ SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM Indicates that the Sensor data is of aver-
age accuracy, and that calibration might improve the readings
➤ SensorManager.SENSOR_STATUS_ACCURACY_HIGH Indicates that the Sensor is reporting with
the highest possible accuracy
➤ SensorManager.SENSOR_STATUS_UNRELIABLE Indicates that the Sensor data is unreliable,
meaning that either calibration is required or readings are not currently possible
To receive Sensor events, register your Sensor Event Listener with the Sensor Manager. Specify the
Sensor object to observe, and the rate at which you want to receive updates. The following example
registers a Sensor Event Listener for the defau lt proximity Sensor at the normal update rate:
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
sensorManager.registerListener(mySensorEventListener,
sensor,
SensorManager.SENSOR_DELAY_NORMAL);
The Sensor Manager includes the following constants (shown in descending order of responsiveness) to
let you select a suitable update rate:
➤ SensorManager.SENSOR_DELAY_FASTEST Specifies the fastest possible Sensor update rate
➤ SensorManager.SENSOR_DELAY_GAME Selects an update rate suitable for use in controlling
games
➤ SensorManager.SENSOR_DELAY_NORMAL Specifies the default update rate
➤ SensorManager.SENSOR_DELAY_UI Specifies a rate suitable for updating UI features
The rate you select is not binding; the Sensor Manager may return results faster or slower than you
specify, though it will tend to be faster. To minimize the associated resource cost of using the Sensor in
your application you should try to select the slowest suitable rate.
It’s also important to unregister your Sensor Event L isteners when your application no longer needs to
receive updates:
sensorManager.unregisterListener(mySensorEventListener);
It’s good practice to register and unregister your Sensor Event Listener in the onResume and onPause
methods of your Activities to ensure they’re being used only when the Activity is active.
INTERPRETING SENSOR VALUES
The length and composition of the values returned in the onSensorChangedevent vary depending on
the Sensor being monitored.
The details are summarized in Table 14-1. Further details on the use of the accelerometer, orientation,
and magnetic field Sensors can be found in the following sections.
The Android documentation describes thevalues returned by each sensor-type with
some additional commentary at http://developer.android.com/reference/
android/hardware/Sensor.html
TABLE 14-1: Sensor Return Values
SENSOR-TYPE VALUE COUNT VALUE COMPOSITION COMMENTARY
TYPE_ACCELEROMETER 3 value[0] : Lateral
value[1] : Longitudinal
value[2] : Vertical
Acceleration along three
axes in m/s
2
. The Sensor
Manager includes a set of
gravity constants of the form
SensorManager.GRAVITY_*
TYPE_GYROSCOPE 3 value[0] : Azimuth
value[1] : Pitch
value[2] : Roll
Device orientation in degrees
along three axes.
TYPE_ LIGHT 1 value[0] : Illumination Measured in lux. The Sensor
Manager includes a set of con-
stants representing different
standard illuminations of the
form SensorManager.LIGHT_*
TYPE_MAGNETIC_FIELD 3 value[0] : Lateral
value[1] : Longitudinal
value[2] : Vertical
Ambient magnetic field mea-
sured in microteslas (μT).
TYPE_ORIENTATION 3 value[0] : Azimuth
value[1] : Roll
value[2] : Pitch
Device orientation in degrees
along three axes.
TYPE_PRESSURE 1 value[0] : Pressure Measured in kilopascals (KP).
TYPE_PROXIMITY 1 value[0] : Distance Measured in meters.
TYPE_TEMPERATURE 1 value[0] : Temperature Measured in degrees Celsius.
Đăng ký:
Bài đăng (Atom)