detect Shake in android

后端 未结 3 1831
孤城傲影
孤城傲影 2021-01-14 08:43

I am trying to hit an API when user shake a device 10 times. I have tried many git sample and stack overflow solution but non of them did solve my problem. Some of them dete

3条回答
  •  没有蜡笔的小新
    2021-01-14 09:12

    have a static variable that gets incremented every time a shake is detected.

    static int count = 0;
    public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        long curTime = System.currentTimeMillis();
        if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
    
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];
    
            double acceleration = Math.sqrt(Math.pow(x, 2) +
                    Math.pow(y, 2) +
                    Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
    
            if (acceleration > SHAKE_THRESHOLD) {
                mLastShakeTime = curTime;
                count++;
                if(count==10){
                    //your code goes here
                }
            }
        }
    }
    

提交回复
热议问题