Multiple sensors on an android application

断了今生、忘了曾经 提交于 2019-12-01 11:31:00

问题


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

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