Android accelerometer: SensorManager.DATA_X is deprecated - now what?

android, android-sensors

Solution

The documentation is quite clear on it, create your sensor:

private SensorManager mSensorManager;
private Sensor mSensor;

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

if (mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

And there is your Sensor, register a listener to use it:

mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);

You can then use OnSensorChanged to get values:

  @Override
  public final void onSensorChanged(SensorEvent event) {
    // Many sensors return 3 values, one for each axis.
    float xaccel = event.values[0];
    // Do something with this sensor value.
  }

Problem

I have written an accelerometer app (for learning purposes) using some of the suggestions from StackOverflow. Everything works fine but I get the "SensorManager.DATA_X is deprecated" message as a warning in my code: ``` // setup the textviews for displaying the accelerations mAccValueViews[SensorManager.DATA_X] = (TextView) findViewById(R.id.accele_x_value); mAccValueViews[SensorManager.DATA_Y] = (TextView) findViewById(R.id.accele_y_value); mAccValueViews[SensorManager.DATA_Z] = (TextView) findViewById(R.id.accele_z_value); ``` I have tried searching here and elsewhere for what I should do instead of using "SensorManager.DATA_X" but I can't seem to find any instructions. The official guide says to use "sensor" instead but I can't figure out how! If anyone can suggest what the new "official" way of doing the above is then I would be very grateful. Edit After re-reading the documentation (properly this time!) I noticed that "SensorManager.DATA_X" just returns an int which is the index of the X value in the array returned by onSensorChanged(int, float[]). I was able to change the above code to this, which works perfectly and without any deprecated warnings: ``` // setup the textviews for displaying the accelerations mAccValueViews[0] = (TextView) findViewById(R.id.accele_x_value); mAccValueViews[1] = (TextView) findViewById(R.id.accele_y_value); mAccValueViews[2] = (TextView) findViewById(R.id.accele_z_value); ```

Original source