开发者

Problem registering multiple sensor listeners on Android

开发者 https://www.devze.com 2023-02-16 05:04 出处:网络
I am trying to register multiple sensor listeners in one sensor manager, but this code won\'t work: boolean linearAccelerationRegistered = mSensorManager.registerListener(this, mAccelerometer, Sensor

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 开发者_Python百科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);
0

精彩评论

暂无评论...
验证码 换一张
取 消