简体   繁体   English

在Android上注册多个传感器侦听器时出现问题

[英]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: 如果您有一个用于多个传感器的侦听器实例,则应检查SensorEvent以确定哪些传感器报告了更改:

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

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

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