Android加速计:SensorManager.DATA_X已过时-现在呢? [英] Android accelerometer: SensorManager.DATA_X is deprecated - now what?
问题描述
我已经使用StackOverflow的一些建议编写了一个加速度计应用程序(出于学习目的).一切正常,但我的代码中收到"SensorManager.DATA_X已弃用"消息作为警告:
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);
我尝试在此处和其他位置搜索应该怎么做,而不是使用"SensorManager.DATA_X",但我似乎找不到任何指令.
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.
编辑 在重新阅读了文档(这次是正确的!)之后,我注意到"SensorManager.DATA_X"仅返回一个int,它是onSensorChanged(int,float [])返回的数组中X值的索引.我能够将上面的代码更改为此,它可以完美运行并且没有任何过时的警告:
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);
推荐答案
文档非常清晰,请创建您的传感器:
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);
然后您可以使用OnSensorChanged获取值:
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.
}
这篇关于Android加速计:SensorManager.DATA_X已过时-现在呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!