In this post we will review how to use the gyroscope and the accelerometer sensors in an android application. These sensors are part of the motion sensors available on some devices.
Sensors on an android application are very easy to use. The following class registers the sensors, and updates its fields with the related sensor coordinates.
package com.my.application;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class Sensors {
float accelerometerValueX = -9;
float accelerometerValueY = -9;
float accelerometerValueZ = -9;
float gyroscopeValueX = -9;
float gyroscopeValueY = -9;
float gyroscopeValueZ = -9;
public void registerReceivers() {
// get context from the app
Context context = ...;
SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
final Sensor gyroscopeSensor = manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
final Sensor accelerometerSensor = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SensorEventListener listener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// Do nothing
}
@Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
try {
if (sensor.getType() == Sensor.TYPE_GYROSCOPE && (gyroscopeSensor != null)) {
gyroscopeValueX = event.values[0];
gyroscopeValueY = event.values[1];
gyroscopeValueZ = event.values[2];
} else if (sensor.getType() == Sensor.TYPE_ACCELEROMETER && (accelerometerSensor != null)) {
accelerometerValueX = event.values[0];
accelerometerValueY = event.values[1];
accelerometerValueZ = event.values[2];
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
if (gyroscopeSensor != null) {
manager.registerListener(listener, gyroscopeSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
if (accelerometerSensor != null) {
manager.registerListener(listener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
}
While getting the sensors coordinates is easy, analyzing their meaning should be done carfully.
The accelerometer coordinates always "feel" the gravity, hence the actual values also include the gravity force. In case of need, the gravity force can be substructed from the accelerometer coordinates.
Using the sensors we can change the behavior of an application to reflect real world activities of the user. We can even track these sensors to try to figure what is the user doing, whether the user is at rest, walking, playing tennis, running, or even swimming. This infomation might even unknowingly break the user privacy, so we need to be careful about storing this information.
No comments:
Post a Comment