1

我已经在 MotionSensors 上注册了一个监听器,现在每当调用 Motion change 方法“onSensorChange()”时。

我知道这些调用来自 SensorManager.java 类。我想知道这些传感器更改事件是如何来自 JNI,JNI 如何触发更改事件并将其发送到 Framework(SensorManager.java)。

4

1 回答 1

1

如果您知道代码的确切位置,则不难检查它是如何工作的。所以主要部分在这里:

       while (true) {
            // wait for an event
            final int sensor = sensors_data_poll(sQueue, values, status, timestamp);

            int accuracy = status[0];
            synchronized (sListeners) {
                if (sensor == -1 || sListeners.isEmpty()) {
                    // we lost the connection to the event stream. this happens
                    // when the last listener is removed or if there is an error
                    if (sensor == -1 && !sListeners.isEmpty()) {
                        // log a warning in case of abnormal termination
                        Log.e(TAG, "_sensors_data_poll() failed, we bail out: sensors=" + sensor);
                    }
                    // we have no more listeners or polling failed, terminate the thread
                    sensors_destroy_queue(sQueue);
                    sQueue = 0;
                    mThread = null;
                    break;
                }
                final Sensor sensorObject = sHandleToSensor.get(sensor);
                if (sensorObject != null) {
                    // report the sensor event to all listeners that
                    // care about it.
                    final int size = sListeners.size();
                    for (int i=0 ; i<size ; i++) {
                        ListenerDelegate listener = sListeners.get(i);
                        if (listener.hasSensor(sensorObject)) {
                            // this is asynchronous (okay to call
                            // with sListeners lock held).
                            listener.onSensorChangedLocked(sensorObject,
                                    values, timestamp, accuracy);
                        }
                    }
                }
            }
        }
        //Log.d(TAG, "exiting main sensor thread");
    }

此代码不断在单独的线程中运行SensorThreadRunnable( while (true))。首先,它调用本机函数,该函数sensors_data_poll返回已更改其值的传感器的标识符(如果没有此类传感器,则返回 -1)。如果它返回 -1,则循环从头开始。如果传感器值已更改,则从传感器标识符创建 sensorObject ( final Sensor sensorObject = sHandleToSensor.get(sensor);)。之后,所有注册的侦听器都有一个循环,如果侦听器正在侦听此传感器对象,则会通知传感器的值已更改。

于 2012-05-30T08:46:05.950 回答