我正在开发一个应用程序,我需要知道2个传感器类型数据的准确性,即TYPE_ACCELEROMETER和TYPE_MAGNETIC_FIELD。我确实将SensorEventListener
注册到两种传感器类型,如下所示:
mSensorManager.registerListener(mSensorEventListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(mSensorEventListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL, SensorManager.SENSOR_DELAY_UI);
然后在我的听众中,我做了类似的事情:
@Override public void onAccuracyChanged(Sensor sensor, int i) {
switch (sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
if (i == SensorManager.SENSOR_STATUS_ACCURACY_HIGH) {
.....
}
break;
case Sensor.TYPE_MAGNETIC_FIELD:
if (i == SensorManager.SENSOR_STATUS_ACCURACY_HIGH) {
.....
}
break;
}
}
但是出于某种原因,每当它被回叫时,sensor.getType()
总是TYPE_ACCELEROMETER
,我从来没有得到另一个......我是否误用了这个回电话?感谢任何建议。
答案 0 :(得分:1)
试试这段代码:
sensorManager = (SensorManager)
getActivity().getSystemService(Context.SENSOR_SERVICE);
sensorAccelerometer =
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorMagnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetic = event.values;
tv.setText("X: "+ magnetic.values[0] + ...);
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
gravity = event.values;
tv2.setText(X: " + gravity.values[0] + ...);
}
}
}
https://stackoverflow.com/a/41860246/7092449
也许切换只能看到一个传感器并打破另一个传感器;)