view raw
郑迎风 郑迎风 - 6 months ago 41
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) {
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)) {
ToastUtils.showToast(mContext, "检测到手机晃动了");

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


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 {
        protected void onCreate(Bundle savedInstanceState) {

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

            TextView tv = new TextView(this);
            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();