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:
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.
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.
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[i] correspond to i=x,y,z but for other sensors check Android documentation.
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.