如何用android中的传感器加速度计检测运动

时间:2016-06-16 19:18:37

标签: java android accelerometer

以下是我的活动代码,但mAccel的值始终为0。我想将mAccel的值与敏感度值进行比较。 有人可以帮我解决这个问题吗?

   private float mAccel;
    private float mAccelCurrent;
    private float mAccelLast;
    private float[] mGravity;
    float sensitivityLevel = 2.0f;

 private SensorManager sensorManager;
 private Sensor accel;

  sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
        accel = sensorManager.getDefaultSensor(1);

        mAccel = 0.00f;
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;
@Override
public void onSensorChanged(SensorEvent event) {
     if (event.sensor.getType() ==1){
            mGravity = event.values.clone();
            // Shake detection
            float x = mGravity[0];
            float y = mGravity[1];
            float z = mGravity[2];
            mAccelLast = mAccelCurrent;
            mAccelCurrent =  FloatMath.sqrt(x*x + y*y + z*z);
            float delta = mAccelCurrent - mAccelLast;
            mAccel = mAccel * 0.9f + delta;

       if(mAccel > sensitivityLevel){
           play_alarm("car alarm");
       }
    }

1 个答案:

答案 0 :(得分:1)

您需要注册监听器

    sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    if(sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size()!=0){
      Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
      sm.registerListener(this,s, SensorManager.SENSOR_DELAY_NORMAL);
    }

您应该使用日志或调试来检查方法是否被调用。