Using the Device Sensor Android

The Android SDK provides access to raw data from sensors on the device. The sensors, and their precision and features, will vary from device to device. Some of the sensors that applications can interact with include the magnetic sensor, which can be used as a compass, and the accelerometer sensor that can detect motion.

You can access the device sensors through the SensorManager object (android. hardware. SensorManager). The SensorManager object listens for data from the sensors. It is a system service, and you can retrieve an instance retrieved with the getSystem Service() method, as shown here:

SensorManager sensors =
(SensorManager) getSystemService(Context.SENSOR_SERVICE);

Working with Different Sensors

The Sensor class (android.hardware.Sensor) defines a number of identifiers for the various sensors that you might find on a device. Not all sensors are available on each device. The most interesting sensors are listed here:

  • TYPE_ACCELEROMETER: Measures acceleration in three directions (values are SI units (m/s2))
  • TYPE_GYROSCOPE: Measures angular orientation in three directions (values are angles in degrees)
  • TYPE_ORIENTATION: Measures orientation in three directions (values are angles in degrees) (deprecated)
  • TYPE_LIGHT: Measures ambient light (values are SI lux units)
  • TYPE_MAGNETIC_FIELD: Measures magnetism in three directions; the compass (values are micro-Tesla (uT))
  • TYPE_PRESSURE: Measures barometric pressure
  • TYPE_PROXIMITY: Measures the distance to an object (values in centimeters, or “near” vs.“far”)
  • TYPE_TEMPERATURE: Measures temperature

The SensorManager class also has a number of constants that can be useful with certain sensors. For instance, you can use the STANDARD_ GRAVITY constant with the accelerometer and the LIGHT_SUNLIGHT constant with the light sensor.

Acquiring Access to a Sensor

You can acquire access to a specific sensor using the SensorManager class method called getDefaultSensor().This method takes a sensor type parameter. For example, you could acquire the default accelerometer sensor as follows:

Sensor accelSensor = sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

Reading Sensor Data

After you have a valid Sensor object, you can read the sensor data periodically. Sensor values are sent back to an application using a SensorEventListener object that the application must implement and register using the registerListener() method.

boolean isAvailable = sensors.registerListener(SensorsActivity.this,
accelSensor, SensorManager.SENSOR_DELAY_NORMAL);

In this case, the accelerometer sensor is watched. The onSensorChanged() method is called at particular intervals defined by the delay value in registerListener(), which is the default value in this case.

The SensorEventListener interface has two required methods you must implement: onAccuracyChanged() and onSensorChanged().The onAccuracyChanged() method is called whenever the accuracy of a given sensor changes. The onSensorChanged() method is called whenever the values of the sensor change. The onSensorChanged() method is generally used to inspect sensor information.

Here is a sample implementation of onSensorChanged() that works for displaying various types of sensor data (not just the accelerometer):

public void onSensorChanged(SensorEvent event) {
StringBuilder sensorMessage =
new StringBuilder(event.sensor.getName()).append(" new values: ");
for (float value : event.values) {
sensorMessage.append(" with accuracy ").append(event.accuracy);
sensorMessage.append(" at timestamp ").append(event.timestamp);
Log.i(DEBUG_TAG, sensorMessage);

The onSensorChanged() method has a single parameter: a SensorEvent object. The SensorEvent class contains all the data about the sensor, including which sensor caused the event, the accuracy of the sensor, the sensor’s current readings and a timestamp. For details about what data to expect for each type of sensor, see the SensorEvent class documentation provided with the Android SDK.

The accelerometer sensor provides three values corresponding to the acceleration minus Gravity on the x, y, and z axes. Output from a typical Android device with an accelerometer sensor is shown in Figure.

Calibrating Sensors

The sensor values won’t be useful to the application until they are calibrated. One way to calibrate is to ask the user to click a button to calibrate the sensor. The application can then store the current values. Then new values can be compared against the original values to see how they have changed from their original values (delta).Although the phone sensors have a specific orientation, this enables the user to use the app in either portrait or landscape mode, regardless of how the user is holding the device.

When registering a sensor, the registerListener() method returns true if the sensor is available and can be activated. It returns false if the sensor isn’t available or cannot be activated.

The sensor values are typically quite sensitive. For most uses, an application probably wants to provide some smoothing of the values to reduce the effects of any noise or shaking. How this is done depends on the purpose of the application. For instance, a simulated bubble level might need less smoothing than a game where too much sensitivity can be frustrating.

Sensor sample application showing accelerometer values.

Sensor sample application showing accelerometer values

The orientation values might be appropriate in cases where only the handset’s orientation is needed but not the rate at which it is changed (accelerometer) or specific direction it’s pointing (compass).

Determining Device Orientation

You can use the SensorManager class to determine the orientation of the device. Although the Sensor.TYPE_ORIENTATION sensor value is deprecated, it is still valid on most popular devices. However, the newest recommended way is to use the getOrientation() method of the SensorManager class instead.

The getOrientation() method takes two parameters: a rotation matrix and an array of three float values (azimuth [z], pitch [x], and roll [y]).

Finding True North

In addition to the SensorManager, there is a helpful class called GeomagneticField available within the android.hardware package. The GeomagneticField class uses the World Magnetic Model to estimate the magnetic field anywhere on the planet, which is typically used to determine magnetic variation between compass north and true north. This model, developed by the United States National Geospatial-Intelligence Agency (NGA), is updated for precision every five years.This model expires in 2015, although results will be accurate enough for most purposes for some time after that date, at which point the Android GeomagneticField class will likely be updated to the latest model.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Android Topics