Multiple Sensors on an Android Application

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); 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 Answer

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] + ...);
        }
    }
}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.