郑迎风 郑迎风 - 1 month ago 18
Android Question

How to find a value for accelerometer?

I was working on a shake phone function.I want to shake the phone with the same strength and get the same feedback so I can run the project on different devices fine. But now, I found that different devices have total different values. So anyone has any advice?
Now show you the code:

public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
float[] values = event.values;
float x = values[0]; //X value
float y = values[1]; //Y value
float z = values[2]; //Z value
if (isShaking(x, sMinVale, event) || isShaking(y, sMinVale, event) || isShaking(z, sMinVale, event)) {
vibrator.vibrate(200);
ToastUtils.showToast(mContext, "检测到手机晃动了");
}

private boolean isShaking(float x, int minValue, SensorEvent event) {
return Math.abs(x) > event.sensor.getMaximumRange();
}

Answer

Why you want to reinvent the wheel?! check out this Library

and here is an example on how to use it

  public class Demo extends Activity implements ShakeDetector.Listener {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            ShakeDetector sd = new ShakeDetector(this);
            sd.start(sensorManager);

            TextView tv = new TextView(this);
            tv.setGravity(CENTER);
            tv.setText("Shake me, bro!");
            setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }

        public void hearShake() {
            Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show();
        }
    }