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.




Không có nhận xét nào:

Đăng nhận xét