steven caesar
steven caesar

Reputation: 85

How to detect motion with sensor accelerometer in android

Here is my code in activity, but the values of mAccel always 0. I want to compare values of mAccel with value of sensivity. Can somebody help me with this problem?

   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");
       }
    }

Upvotes: 1

Views: 564

Answers (1)

Kusan
Kusan

Reputation: 260

You need to register the listener

    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);
    }

You should use logs or debug to check if the method is called.

Upvotes: 1

Related Questions