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

倖福魔咒の 提交于 2021-01-27 07:44:15

问题


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

回答1:


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.
  }


来源:https://stackoverflow.com/questions/13687480/android-accelerometer-sensormanager-data-x-is-deprecated-now-what

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!