监听摇一摇最合适的代码

2019-05-28  本文已影响0人  ironman_

摇一摇要说监听很好监听,但是代码写的不合适有时候很容易就触发,或者手摇酸了都不会触发。

这个策略是,在时间间隔内连续加速限定次,则认为是一次摇动。

比如这里是每隔800毫秒的一次加速认为是连续加速,连续加速三次以上则认为是在摇动。

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; //多长时间间隔内可以认为是连续摇晃
    private static final long ACCELERATE_TIMES_THRESHOLD = 3; //连续加速次数
    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) {

            }
        };
        //注册传感器监听事件
        mSensorManager.registerListener(listener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_UI);
        //注销传感器监听
        //        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, 
    }
}
上一篇下一篇

猜你喜欢

热点阅读