import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener {
private static final int SPEED_SHRESHOLD = 3000;
private static final int UPTATE_INTERVAL_TIME = 70;
String TAG = "ShakeListener";
private long lastUpdateTime;
private float lastX;
private float lastY;
private float lastZ;
private Context mContext;
private OnShakeListener onShakeListener;
private Sensor sensor;
private SensorManager sensorManager;
public interface OnShakeListener {
void onShake();
}
public ShakeListener(Context c) {
this.mContext = c;
start();
}
public void start() {
this.sensorManager = (SensorManager) this.mContext.getSystemService("sensor");
if (this.sensorManager != null) {
this.sensor = this.sensorManager.getDefaultSensor(1);
}
if (this.sensor != null) {
this.sensorManager.registerListener(this, this.sensor, 1);
}
}
public void stop() {
this.sensorManager.unregisterListener(this);
}
public void setOnShakeListener(OnShakeListener listener) {
this.onShakeListener = listener;
}
public void onSensorChanged(SensorEvent event) {
long currentUpdateTime = System.currentTimeMillis();
long timeInterval = currentUpdateTime - this.lastUpdateTime;
if (timeInterval >= 70) {
this.lastUpdateTime = currentUpdateTime;
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
float deltaX = x - this.lastX;
float deltaY = y - this.lastY;
float deltaZ = z - this.lastZ;
this.lastX = x;
this.lastY = y;
this.lastZ = z;
if ((Math.sqrt((double) (((deltaX * deltaX) + (deltaY * deltaY)) + (deltaZ * deltaZ))) / ((double) timeInterval)) * 10000.0d >= 3000.0d) {
this.onShakeListener.onShake();
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
摇一摇监听器
最新推荐文章于 2021-06-01 08:28:00 发布