问题
I am currently developing an android application that uses multiple sensors, I have used
mSensor= mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
in OnCreate
Method to get the sensor and tv.setText("X: "+ sensorEvent.values[0] + ...);
in onSensorChanged
method, to display the accelerometer values in a text view.
How can I add more sensors and display their values in the same way?
How will the program know which sensor I am referring to when I say sensorEvent.values[0]
?
Thank you for any help in advance, Maja
回答1:
You will need to check if the sensor values are of that type of sensor with the event.sensor.getType() method. So if you wanted to access both the Magnetometer and Accelerometer:
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/questions/41859899/multiple-sensors-on-an-android-application