简体   繁体   English

Android 应用程序上的多个传感器

[英]Multiple sensors on an android application

I am currently developing an android application that uses multiple sensors, I have used mSensor= mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);我目前正在开发一个使用多个传感器的 android 应用程序,我使用了mSensor= mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); in OnCreate Method to get the sensor and tv.setText("X: "+ sensorEvent.values[0] + ...);OnCreate方法中获取传感器和tv.setText("X: "+ sensorEvent.values[0] + ...); in onSensorChanged method, to display the accelerometer values in a text view.onSensorChanged方法中,在文本视图中显示加速度计值。

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] ?当我说sensorEvent.values[0]时,程序如何知道我指的是哪个传感器?

Thank you for any help in advance, Maja提前感谢您的任何帮助,玛雅

You will need to check if the sensor values are of that type of sensor with the event.sensor.getType() method.您需要使用 event.sensor.getType() 方法检查传感器值是否属于该类型的传感器。 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] + ...);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM