Module 0268: Accessing sensors from an Android App
Tak Auyeung, Ph.D.
February 27, 2017
1 About this module
- Prerequisites:
- Objectives: This module discusses how to access common sensors from an Android App.
2 Introduction to Sensors
An Android sensor is a device that measures some environmental parameter and convert the physical quantity of the parameter into
a number that can be read from an app. Typical examples include the following:
- Accelerometer: measures acceleration in x, y and z axes.
- Ambient Temperature: measure ambient temperature.
- Gyroscope: measures rate of rotation in x, y and z axes.
- Magnetic field: measures magnetic field in x, y and z axes.
- Pressure: air pressure.
- Relative humidity: how close to condensation.
- Temperature: device temperature.
For more details, visit the Android Developer’s page on sensors.
In Linux, the underlying OS of Android, reading a hardware device is an involved process because Linux and Unix
systems tend to see everything as a “file”. A bit of work is needed to gain access to special devices like sensors. The
Android platform, on the other hand, simplifies access to sensors from a file-based operation to an event-based
operation.
Because an app is, for the most part, an event-driven program, event-driven sensor access makes it easier to develop code to
access sensors. In general, the following steps allow an app access a sensor:
- A SensorManager class provides a magnitude of methods, many of them static. However, this class also produces
Sensor objects.
- A Sensor object represents a particular sensor. However, such an object does not actually report the values associated
with a sensor. A Sensor object reports various static aspects and general aspects of a sensor, and it is needed to
register a SensorEventListener to the sensor manager.
- A SensorEventListener, like a OnClickListener, is an interface that specifies a parameter that is an object
implementing the two required methods. One method corresponds to what to do when the value of a sensor changes,
while the other method corresponds to what to do when the accuracy of a sensor changes. Both methods must be
specified, but they can be empty.
- A SensorEvent object is passed as parameter to the onSensorChangedmethod of an object that passes the
SensorEventListener interface. This is where a value of a sensor is reported.
3 A sample program
A sample program is written to demonstrate how to make use of sensors. This program has a single button to trigger the listing of
all available sensors. In the list view, clicking an item displays the value of the chosen sensor. Value changes are updated
dynamically. It is a simple app in many ways, but it illustrates coding techniques of using sensors as well as using the ListView
class and its associated classes.