How to refresh app upon shaking the device?

前端 未结 16 2059
眼角桃花
眼角桃花 2020-11-22 13:42

I need to add a shake feature that will refresh my Android application.

All I find of documentation involves implementing the SensorListener, but Eclips

16条回答
  •  鱼传尺愫
    2020-11-22 14:22

    I have tried several implementations, but would like to share my own. It uses G-force as unit for the threshold calculation. It makes it a bit easier to understand what is going on, and also with setting a good threshold.

    It simply registers a increase in G force and triggers the listener if it exceeds the threshold. It doesn't use any direction thresholds, cause you don't really need that if you just want to register a good shake.

    Of-course you need the standard registering and UN-registering of this listener in the Activity.

    Also, to check what threshold you need, I recommend the following app (I am not in any way connected to that app)

        public class UmitoShakeEventListener implements SensorEventListener {
    
        /**
         * The gforce that is necessary to register as shake. (Must include 1G
         * gravity)
         */
        private final float shakeThresholdInGForce = 2.25F;
    
        private final float gravityEarth = SensorManager.GRAVITY_EARTH;
    
        private OnShakeListener listener;
    
        public void setOnShakeListener(OnShakeListener listener) {
            this.listener = listener;
        }
    
        public interface OnShakeListener {
            public void onShake();
        }
    
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // ignore
    
        }
    
        @Override
        public void onSensorChanged(SensorEvent event) {
    
            if (listener != null) {
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
    
                float gX = x / gravityEarth;
                float gY = y / gravityEarth;
                float gZ = z / gravityEarth;
    
                //G-Force will be 1 when there is no movement. (gravity)
                float gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ); 
    
    
    
                if (gForce > shakeThresholdInGForce) {
                    listener.onShake();
    
                }
            }
    
        }
    
    }
    

提交回复
热议问题