简体   繁体   中英

Problem registering multiple sensor listeners on Android

I am trying to register multiple sensor listeners in one sensor manager, but this code won't work:

boolean linearAccelerationRegistered = mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
        boolean rotationVecRegistered = mSensorManager.registerListener(this, mOrientation, SensorManager.SENSOR_DELAY_FASTEST);

It only registers accelerometer. It registered rotation when I commented out the first statement

Technically you register only one listener to the sensor manager, but this listener listens to multiple sensors. My first idea was, that you have to use different listener classes for each sensor. I had a sample activity at hand, where I made use of four sensors. I registered each of them with a different listener at the sensor manager. That worked. Now I tried your approach with one listener for all of them and that worked as well.

Its hard to tell what might went wrong with only these two lines. Maybe you think, the orientation sensor wasn't registered, because the listener received multiple value changes from the accelerometer in a row, before the orientation changes were queued!?

If you have one listener instance for multiple sensors, you should inspect the SensorEvent to find out, which of the sensors reported the change:

public void onSensorChanged(SensorEvent event) {
    Sensor source = event.sensor;
    if (source.equals(mAccelerometer)) {
       // do your stuff
    } else if (source.equals(mOrientation)) {
       // do your stuff
    }
}

Try to register each sensor with it's own listener and see, if you get different results (but it should also work the way you pointed out...):

mSensorManager.registerListener(mAccelerometerListener, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(mOrientationListener, mOrientation, SensorManager.SENSOR_DELAY_FASTEST);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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