Using Android’s sensors

Most of the smartphones have a wide array of sensors to measure motion, position and envirommental conditions. The Android platform supports several sensors, both hardware-based and virtual, such as accelerometer, gyroscope, proximity, temperature, illuminance or humidity.

Managing sensors in Android is not difficult and there are good references and documentation on the developers website.  The basic steps to get the sensor values, such as the accelerometer’s data or the temperature, are summarized in this post.

1.List the sensors

Before using the senors it’s important to know which are available in the device. To check it on the app:

List sensors

2. Enable the sensors

To enable the sensors and get the data we have to obtain instances of SensorManager and sensors we want to access. Then enable them and register the listeners to start collecting the data. In the example we enable accelerometer, orientation and temperature sensors.
Enable sensors

It is important not to forget to unregister the listeners when the app is not working or when sensor values are not needed. At least it is needed to register them on the onCreate() and onResume() methods and unregister them on the onPause() method. Unregister sensors

3. Get the sensor values

The OnSensorChanged() method is used to get the sensor values, the timestamp, the type of sensor or the accuracity. The contents of the values array depend on which sensor type is being monitored. For the accelerometer values, values] correspond to i=x,y,z but for other sensors check Android documentationGet values

4. Use the sensors data

Usually sensor values are used in the app but it also can be stored in a file to analyze, for example, on the computer. Following there are two examples, the first one shows the data on the device screen and the second one correspond to a plot of the collected accelerometer data while walking.

StepsAcc

SensorValuesScreen
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s