Lecture Note 09 - CSE 401
Lecture Note 09 - CSE 401
Most Android-powered devices have built-in sensors that measure motion, orientation, and
various environmental conditions. These sensors are capable of providing raw data with
high precision and accuracy, and are useful if you want to monitor three-dimensional device
movement or positioning, or you want to monitor changes in the ambient environment near
a device. For example, a game might track readings from a device's gravity sensor to infer
complex user gestures and motions, such as tilt, shake, rotation, or swing. Likewise, a
weather application might use a device's temperature sensor and humidity sensor to
calculate and report the dewpoint, or a travel application might use the geomagnetic field
sensor and accelerometer to report a compass bearing.
Motion sensors
These sensors measure acceleration forces and rotational forces along three axes. This category
includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
Environmental sensors
These sensors measure various environmental parameters, such as ambient air temperature and
pressure, illumination, and humidity. This category includes barometers, photometers, and
thermometers.
Position sensors
These sensors measure the physical position of a device. This category includes orientation sensors
and magnetometers.
You can access sensors available on the device and acquire raw sensor data by using the Android
sensor framework. The sensor framework provides several classes and interfaces that help you perform
a wide variety of sensor-related tasks. For example, you can use the sensor framework to do the
following:
Determine an individual sensor's capabilities, such as its maximum range, manufacturer, power
requirements, and resolution.
Acquire raw sensor data and define the minimum rate at which you acquire sensor data.
Register and unregister sensor event listeners that monitor sensor changes.
This topic provides an overview of the sensors that are available on the Android platform. It also provides
an introduction to the sensor framework.
Introduction to Sensors
The Android sensor framework lets you access many types of sensors. Some of these sensors are
hardware-based and some are software-based. Hardware-based sensors are physical components built
into a handset or tablet device. They derive their data by directly measuring specific environmental
properties, such as acceleration, geomagnetic field strength, or angular change. Software-based sensors
are not physical devices, although they mimic hardware-based sensors. Software-based sensors derive
their data from one or more of the hardware-based sensors and are sometimes called virtual sensors or
synthetic sensors. The linear acceleration sensor and the gravity sensor are examples of software-based
sensors. Table 1 summarizes the sensors that are supported by the Android platform.
Few Android-powered devices have every type of sensor. For example, most handset devices and
tablets have an accelerometer and a magnetometer, but fewer devices have barometers or
thermometers. Also, a device can have more than one sensor of a given type. For example, a device can
have two gravity sensors, each one having a different range.
Sensor Framework
You can access these sensors and acquire raw sensor data by using the Android sensor framework. The
sensor framework is part of theandroid.hardware package and includes the following classes and
interfaces:
SensorManager
You can use this class to create an instance of the sensor service. This class provides various
methods for accessing and listing sensors, registering and unregistering sensor event listeners,
and acquiring orientation information. This class also provides several sensor constants that are
used to report sensor accuracy, set data acquisition rates, and calibrate sensors.
Sensor
Sensor Type Description Common Uses
TYPE_ACCELEROM Hardware Measures the acceleration force in m/s2 that is applied to a device Motion
ETER on all three physical axes (x, y, and z), including the force of detection
gravity. (shake, tilt,
etc.).
TYPE_AMBIENT_T Hardware Measures the ambient room temperature in degrees Celsius (°C). Monitoring air
EMPERATURE See note below. temperatures.
TYPE_GRAVITY Software Measures the force of gravity in m/s2 that is applied to a device on Motion
or all three physical axes (x, y, z). detection
Hardware (shake, tilt,
etc.).
TYPE_GYROSCOPE Hardware Measures a device's rate of rotation in rad/s around each of the Rotation
three physical axes (x, y, and z). detection (spin,
turn, etc.).
TYPE_LIGHT Hardware Measures the ambient light level (illumination) in lx. Controlling
screen
brightness.
TYPE_LINEAR_AC Software Measures the acceleration force in m/s2 that is applied to a device Monitoring
CELERATION or on all three physical axes (x, y, and z), excluding the force of acceleration
Hardware gravity. along a single
axis.
TYPE_MAGNETIC_ Hardware Measures the ambient geomagnetic field for all three physical Creating a
FIELD axes (x, y, z) in μT. compass.
You can use this class to create an instance of a specific sensor. This class provides various
methods that let you determine a sensor's capabilities.
TYPE_ORIENTATI Software Measures degrees of rotation that a device makes around all three Determining
ON physical axes (x, y, z). As of API level 3 you can obtain the device position.
inclination matrix and rotation matrix for a device by using the
gravity sensor and the geomagnetic field sensor in conjunction
with the getRotationMatrix() method.
TYPE_PRESSURE Hardware Measures the ambient air pressure in hPa or mbar. Monitoring air
pressure
changes.
TYPE_PROXIMITY Hardware Measures the proximity of an object in cm relative to the view Phone position
screen of a device. This sensor is typically used to determine during a call.
whether a handset is being held up to a person's ear.
TYPE_RELATIVE_ Hardware Measures the relative ambient humidity in percent (%). Monitoring
HUMIDITY dewpoint,
absolute, and
relative
humidity.
TYPE_ROTATION_ Software Measures the orientation of a device by providing the three Motion
VECTOR or elements of the device's rotation vector. detection and
Hardware rotation
detection.
TYPE_TEMPERATU Hardware Measures the temperature of the device in degrees Celsius (°C). Monitoring
RE This sensor implementation varies across devices and this sensor temperatures.
was replaced with theTYPE_AMBIENT_TEMPERATURE sensor in API
Level 14
SensorEvent
The system uses this class to create a sensor event object, which provides information about a
sensor event. A sensor event object includes the following information: the raw sensor data, the
type of sensor that generated the event, the accuracy of the data, and the timestamp for the
event.
SensorEventListener
You can use this interface to create two callback methods that receive notifications (sensor
events) when sensor values change or when sensor accuracy changes.
In a typical application you use these sensor-related APIs to perform two basic tasks:
Identifying sensors and sensor capabilities at runtime is useful if your application has features
that rely on specific sensor types or capabilities. For example, you may want to identify all of
the sensors that are present on a device and disable any application features that rely on
sensors that are not present. Likewise, you may want to identify all of the sensors of a given
type so you can choose the sensor implementation that has the optimum performance for your
application.
Monitoring sensor events is how you acquire raw sensor data. A sensor event occurs every
time a sensor detects a change in the parameters it is measuring. A sensor event provides you
with four pieces of information: the name of the sensor that triggered the event, the timestamp
for the event, the accuracy of the event, and the raw sensor data that triggered the event.
To monitor raw sensor data you need to implement two callback methods that are exposed through
the SensorEventListener interface:onAccuracyChanged() and onSensorChanged(). The Android system
calls these methods whenever the following occurs:
In this case the system invokes the onAccuracyChanged() method, providing you with a reference to
the Sensor object that changed and the new accuracy of the sensor. Accuracy is represented by one
of four status
constants: SENSOR_STATUS_ACCURACY_LOW, SENSOR_STATUS_ACCURACY_MEDIUM ,SENSOR_STATUS_ACCURA
CY_HIGH, or SENSOR_STATUS_UNRELIABLE .
The following code shows how to use the onSensorChanged() method to monitor data from the light
sensor. This example displays the raw sensor data in a TextView that is defined in the main.xml file
as sensor_data.
@Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
float lux = event.values[0];
// Do something with this sensor value.
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
}
In this example, the default data delay (SENSOR_DELAY_NORMAL) is specified when
the registerListener() method is invoked. The data delay (or sampling rate) controls the interval at
which sensor events are sent to your application via the onSensorChanged() callback method. The
default data delay is suitable for monitoring typical screen orientation changes and uses a delay of
200,000 microseconds. You can specify other data delays, such as SENSOR_DELAY_GAME (20,000
microsecond delay), SENSOR_DELAY_UI (60,000 microsecond delay), or SENSOR_DELAY_FASTEST (0
microsecond delay). As of Android 3.0 (API Level 11) you can also specify the delay as an absolute value
(in microseconds).
The delay that you specify is only a suggested delay. The Android system and other applications can
alter this delay. As a best practice, you should specify the largest delay that you can because the system
typically uses a smaller delay than the one you specify (that is, you should choose the slowest sampling
rate that still meets the needs of your application). Using a larger delay imposes a lower load on the
processor and therefore uses less power.
There is no public method for determining the rate at which the sensor framework is sending sensor
events to your application; however, you can use the timestamps that are associated with each sensor
event to calculate the sampling rate over several events. You should not have to change the sampling
rate (delay) once you set it. If for some reason you do need to change the delay, you will have to
unregister and reregister the sensor listener.
It's also important to note that this example uses the onResume() and onPause() callback methods to
register and unregister the sensor event listener. As a best practice you should always disable sensors
you don't need, especially when your activity is paused. Failing to do so can drain the battery in just a few
hours because some sensors have substantial power requirements and can use up battery power
quickly. The system will not disable sensors automatically when the screen turns off
The accelerometer can only provide you information regarding the directional movement of
the mobile but cannot tell you anything about the lateral orientation or tilt during. For this
purpose you will need the gyroscope.
Both these sensors with assistance of each other. By using an accelerometer only, you will be
able to produce a clean output but it will be very sluggish or it will be very noisy but will be
very responsive. You will need to combine 3-axis accelerometer and the 3-axis gyro for
producing an output that is both, clean and responsive.
Compass or Magnetometer:
As the name of the sensor suggests, it is a simple digital compass which is based on a sensor
called magnetometer and makes the mobile to work as a simple traditional compass It
provides simple orientation in relation to the magnetic field of our Earth. This sensor is mostly
used in the digital maps for letting you know that which way is North.
Barometer:
Higher-end phones have a built-in barometer – a sensor that can measure atmospheric
pressure. Contrary to what you may suggest, it has nothing to do with weather. Instead, the
data measured by it is used to determine how high the device is above sea level, to help
the GPS chip inside the device get a faster lock by instantly delivering altitude data, which in
turn results in improved GPS accuracy. On a related note, the Motorola XOOM and the
Samsung Galaxy Nexus were among the first Android devices to feature this sensor. This
sensor is found in only some selective latest mobiles.
The Thermometer
Some folks might remember that the Samsung Galaxy S4 bragged with a thermometer for
measuring ambient temperature. However, there’s a thermometer in pretty much any
smartphone, and some handsets might have more than one of them. The difference is that
they’re used to monitor the temperature inside the device and its battery. If a component is
detected to be overheating, the system shuts itself down to prevent damage. And speaking of
the Galaxy S4, it pioneered the use of an air humidity sensor in a smartphone.
Back-Illuminated sensor
Back-illuminated sensor is one of the new feature that every camera contains. It is a type
of digital image sensor which changes or increase the light captured while capturing a
photograph. Earlier it was designed for security cameras and astronomical purposes. Sony is
the first company to implement this technology in 2009.
PROXIMITY:
The proximity sensor is used to find out that how much your phone close to your body.
When you bring the mobile closed to your ear, the proximity sensor detects it and
automatically closes the display for saving the battery. This thing also helps in avoiding the
accidental touch cause by your ear while answering a phone call.
The Heart Rate Sensor
For the first time in the history of the smartphone, Galaxy S5 features the heart rate sensor,
which enables users to monitor their physical information. This opens up a lot of
opportunities in terms of the benefit that can be produced from the utilization of such
information.
Users can check their heart rate through the S Health app. By following the instructions that
the S Health provides, users simply need to gently press their finger against the heart rate
sensor, which is located on the bottom of the camera on the back panel.
The Heart Rate Sensor consists of the Red LED and Pulse Sensor. First, the Red LED shoots the
light to the user’s skin. Then the pulse sensor measures the movement of the red blood cells
of the capillaries, which is underneath the finger, according to the pulsation, to measure the
heart rate by calculating the frequency of the wave per minute.
The measured heart rate sensor is displayed on smartphone, and heart rate measurements
can be recorded and saved into the smartphone. Users can measure their heart rate before
and after a workout to check out their health and workout status.
The Pedometer
Used for counting the number of steps that the user has taken. Such data is usually obtained
by the device’s accelerometer, but a dedicated pedometer is a lot more accurate and power
efficient. The Google Nexus 5 is among the few phones that have a true pedometer built into
them.
A sensor that you wouldn’t expect to find on a smartphone is one capable of detecting
harmful radiation. Yet there’s a phone that sports one – the Sharp Pantone 5. Released only
in Japan, it features a dedicated button which launches an app used to measure the current
radiation level in the area.
RGB Light Sensor: Measure the red, green, blue and white intensity of the light source,
used mainly to make adjustments in the Cameras.
References
1. https://developer.android.com/guide/topics/sensors/sensors_overview.html
2. https://testingmobileapps.wordpress.com/2016/02/17/smartphones-sensors-list/