搖一搖要說監(jiān)聽很好監(jiān)聽腻格,但是代碼寫的不合適有時候很容易就觸發(fā),或者手搖酸了都不會觸發(fā)啥繁。
這個策略是菜职,在時間間隔內(nèi)連續(xù)加速限定次,則認(rèn)為是一次搖動旗闽。
比如這里是每隔800毫秒的一次加速認(rèn)為是連續(xù)加速酬核,連續(xù)加速三次以上則認(rèn)為是在搖動。
public class Shaker {
private long lastInvoke = 0;
private long lastUpdate;
private static final int SHAKE_THRESHOLD = 800;
private static final long SEQUENCE_SHAKE_GAP = 800; //多長時間間隔內(nèi)可以認(rèn)為是連續(xù)搖晃
private static final long ACCELERATE_TIMES_THRESHOLD = 3; //連續(xù)加速次數(shù)
private float last_x, last_y, last_z;
private int shakeTimes;
private Context applicationContext;
public void init(Application application) {
this.applicationContext = application;
ConfigUtils.initContext(application);
SensorManager mSensorManager = (SensorManager) application.getSystemService(Context.SENSOR_SERVICE);
SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
last_x = x;
last_y = y;
last_z = z;
if (speed > SHAKE_THRESHOLD) {
// Log.i("shake", "shake detected w/ speed: " + speed);
recordShake();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
//注冊傳感器監(jiān)聽事件
mSensorManager.registerListener(listener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
//注銷傳感器監(jiān)聽
// mSensorManager.unregisterListener(listener);
}
public void recordShake() {
// Log.i("shake", "shake invoked");
long currentTime = System.currentTimeMillis();
if (lastInvoke == 0 || currentTime - lastInvoke < SEQUENCE_SHAKE_GAP) {
shakeTimes++;
} else {
shakeTimes = 1;
}
lastInvoke = currentTime;
// Log.i("shake", "shakeTimes:" + shakeTimes);
if (shakeTimes > ACCELERATE_TIMES_THRESHOLD) {
shakeTimes = 0;
onShakeInvoked();
}
}
private void onShakeInvoked() {
//todo do something适室,
}
}