Skip to content

Instantly share code, notes, and snippets.

@omaraflak
Last active March 18, 2017 13:42
Show Gist options
  • Save omaraflak/df5002c5efe06a03b60ca62efc64dcb4 to your computer and use it in GitHub Desktop.
Save omaraflak/df5002c5efe06a03b60ca62efc64dcb4 to your computer and use it in GitHub Desktop.
Listener for shake events.
/**
* Created by Omar on 07/03/2017.
*/
public class ShakeDetector implements SensorEventListener {
private static final int SENSITIVITY = 18;
private static final int INTERVAL_M = 2500;
private SensorManager sensorManager;
private Sensor accelerometer;
private Listener listener;
private float accelerometerCurrent;
private float value;
private long lastShake;
public ShakeDetector(SensorManager sensorManager) {
this.sensorManager = sensorManager;
this.lastShake = 0;
}
public void setListener(Listener listener) {
this.listener = listener;
}
@Override
public void onSensorChanged(SensorEvent event) {
float ay = event.values[1];
float accelerometerLast = accelerometerCurrent;
accelerometerCurrent = Math.abs(ay);
value = value * 0.9f + accelerometerCurrent - accelerometerLast;
if(value > SENSITIVITY){
if(listener != null){
long now = getTimestamp();
if(now - lastShake > INTERVAL_M){
lastShake = now;
listener.onShake();
}
}
}
}
@Override public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void start() {
if (accelerometer != null) {
return;
}
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null) {
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
}
}
public void stop() {
if (accelerometer != null) {
sensorManager.unregisterListener(this, accelerometer);
accelerometer = null;
}
}
private long getTimestamp(){
return new Date().getTime();
}
public interface Listener {
void onShake();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment