Decide if your device is static or not using the accelerometer
suggest changeAdd the following code to the onCreate()
/onResume()
method:
SensorManager sensorManager;
Sensor mAccelerometer;
final float movementThreshold = 0.5f; // You may have to change this value.
boolean isMoving = false;
float[] prevValues = {1.0f, 1.0f, 1.0f};
float[] currValues = new float[3];
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
You may have to adjust the sensitivity by adapting the movementThreshold
by trial and error. Then, override the onSensorChanged()
method as follows:
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor == mAccelerometer) {
System.arraycopy(event.values, 0, currValues, 0, event.values.length);
if ((Math.abs(currValues[0] - prevValues[0]) > movementThreshold) ||
(Math.abs(currValues[1] - prevValues[1]) > movementThreshold) ||
(Math.abs(currValues[2] - prevValues[2]) > movementThreshold)) {
isMoving = true;
} else {
isMoving = false;
}
System.arraycopy(currValues, 0, prevValues, 0, currValues.length);
}
}
If you want to prevent your app from being installed on devices that do not have an accelerometer, you have to add the following line to your manifest:
<uses-feature android:name="android.hardware.sensor.accelerometer" />
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents