registerListener用来注册要监听的sensor,在Android应用中,我们是这么使用来注册一个需要监听的sensor的
registerListener(this, tp,SensorManager.SENSOR_DELAY_FASTEST);
第一个是一个实现了SensorEventListener 接口的类,当有数据到来时会调用onSensorChanged 方法,tp是我们获取到的需要注册的sensor,,第三个是需要的反应速率
我们来看一下registerListener在整个流程中怎么实现的
我们先看一下流程图:
SensorManager .registerListener public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate) { return registerListener(listener, sensor, rate, null); }
这里直接调用它的另外一个registerListener接口
SensorManager .registerListener public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate, Handler handler) { if (listener == null || sensor == null) { return false; } int delay = -1; switch (rate) { case SENSOR_DELAY_FASTEST: delay = 0; break; case SENSOR_DELAY_GAME: delay = 20000; break; case SENSOR_DELAY_UI: delay = 66667; break; case SENSOR_DELAY_NORMAL: delay = 200000; break; default: delay = rate; break; } return registerListenerImpl(listener, sensor, delay, handler); }
这里根据rate设置delay的大小,然后调用registerListenerImpl,registerListenerImpl是一个抽象的方法,注意到了4.0里面getSystemService返回的其实是一个SystemSensorManager类,所以这里我们调用的是它的registerListenerImpl
SystemSensorManager. registerListenerImpl protected boolean registerListenerImpl(SensorEventListener listener, Sensor sensor, int delay, Handler handler) { boolean result = true; synchronized (sListeners) { // look for this listener in our list ListenerDelegate l = null; for (ListenerDelegate i : sListeners) {//首先查看sListeners中是否有这个监听类 if (i.getListener() == listener) { l = i; break; } } // if we don't find it, add it to the list if (l == null) {//sListeners中没有这个监听类 l = new ListenerDelegate(listener, sensor, handler);//建立一个监听的委托类 sListeners.add(l);//添加到sListeners // if the list is not empty, start our main thread if (!sListeners.isEmpty()) { if (sSensorThread.startLocked()) {//启动监听线程 if (!enableSensorLocked(sensor, delay)) {//使能相应的sensor // oops. there was an error sListeners.remove(l); result = false; } } else { // there was an error, remove the listener sListeners.remove(l); result = false; } } else { // weird, we couldn't add the listener result = false; } } else if (!l.hasSensor(sensor)) { l.addSensor(sensor); if (!enableSensorLocked(sensor, delay)) { // oops. there was an error l.removeSensor(sensor); result = false; } } } return result; }
这里如果这个sListeners监听类还没有添加过,则新建一个监听的委托类ListenerDelegate,
ListenerDelegate(SensorEventListener listener, Sensor sensor, Handler handler) { mSensorEventListener = listener; Looper looper = (handler != null) ? handler.getLooper() : mMainLooper; // currently we create one Handler instance per listener, but we could // have one per looper (we'd need to pass the ListenerDelegate // instance to handleMessage and keep track of them separately). mHandler = new Handler(looper) { @Override public void handleMessage(Message msg) { final SensorEvent t = (SensorEvent)msg.obj; final int handle = t.sensor.getHandle(); switch (t.sensor.getType()) { // Only report accuracy for sensors that support it. case Sensor.TYPE_MAGNETIC_FIELD: case Sensor.TYPE_ORIENTATION: // call onAccuracyChanged() only if the value changes final int accuracy = mSensorAccuracies.get(handle); if ((t.accuracy >= 0) && (accuracy != t.accuracy)) { mSensorAccuracies.put(handle, t.accuracy); mSensorEventListener.onAccuracyChanged(t.sensor, t.accuracy); } break; default: // For other sensors, just report the accuracy once if (mFirstEvent.get(handle) == false) { mFirstEvent.put(handle, true); mSensorEventListener.onAccuracyChanged( t.sensor, SENSOR_STATUS_ACCURACY_HIGH); } break; } mSensorEventListener.onSensorChanged(t); sPool.returnToPool(t); } }; addSensor(sensor); }
这里handle为NULl,looper用的是主线程的,然后new 了一个Handle,并重写了handleMessage方法,这里当收到消息时,就会对相应的消息进行处理,最终都会调用mSensorEventListener.onSensorChanged(t)这个mSensorEventListener就是我们传进来的,也就是我们实现了SensorEventListener接口的类,所以这里就回到了应用程序的onSensorChanged把数据返回给应用。
再回到SystemSensorManager. registerListenerImpl,监听委托类建立好之后,我们就启动sensor线程,监听数据的到来,然后使能sensor
private boolean enableSensorLocked(Sensor sensor, int delay) { boolean result = false; for (ListenerDelegate i : sListeners) { if (i.hasSensor(sensor)) { String name = sensor.getName(); int handle = sensor.getHandle(); result = sensors_enable_sensor(sQueue, name, handle, delay); break; } } return result; }
sensors_enable_sensor是一个jni的函数
static jboolean sensors_enable_sensor(JNIEnv *env, jclass clazz, jint nativeQueue, jstring name, jint sensor, jint delay) { sp<SensorEventQueue> queue(reinterpret_cast<SensorEventQueue *>(nativeQueue)); if (queue == 0) return JNI_FALSE; status_t res; if (delay >= 0) { res = queue->enableSensor(sensor, delay); } else { res = queue->disableSensor(sensor); } return res == NO_ERROR ? true : false; }
这里delay>0调用queue->enableSensor
status_t SensorEventQueue::enableSensor(int32_t handle, int32_t us) const { status_t err = mSensorEventConnection->enableDisable(handle, true); if (err == NO_ERROR) { mSensorEventConnection->setEventRate(handle, us2ns(us)); } return err; }
这里通过binder调用到SensorEventConnection的enableDisable
status_t SensorService::SensorEventConnection::enableDisable( int handle, bool enabled) { status_t err; if (enabled) { err = mService->enable(this, handle); } else { err = mService->disable(this, handle); } return err; }
这们这里是enable
status_t SensorService::enable(const sp<SensorEventConnection>& connection, int handle) { if (mInitCheck != NO_ERROR) return mInitCheck; Mutex::Autolock _l(mLock); SensorInterface* sensor = mSensorMap.valueFor(handle);//找到这个sensor status_t err = sensor ? sensor->activate(connection.get(), true) : status_t(BAD_VALUE);//调用activate方法 if (err == NO_ERROR) { SensorRecord* rec = mActiveSensors.valueFor(handle); if (rec == 0) { rec = new SensorRecord(connection);//新建一个SensorRecord mActiveSensors.add(handle, rec);//添加到mActiveSensors if (sensor->isVirtual()) { mActiveVirtualSensors.add(handle, sensor); } } else { if (rec->addConnection(connection)) { // this sensor is already activated, but we are adding a // connection that uses it. Immediately send down the last // known value of the requested sensor if it's not a // "continuous" sensor. if (sensor->getSensor().getMinDelay() == 0) { sensors_event_t scratch; sensors_event_t& event(mLastEventSeen.editValueFor(handle)); if (event.version == sizeof(sensors_event_t)) { connection->sendEvents(&event, 1); } } } } if (err == NO_ERROR) { // connection now active if (connection->addSensor(handle)) { // the sensor was added (which means it wasn't already there) // so, see if this connection becomes active if (mActiveConnections.indexOf(connection) < 0) { mActiveConnections.add(connection);//添加到mActiveConnections 在threadLoop中会用到 } } } } return err; }
这里使能sensor,然后将相应的变量添加到mActiveSensors和mActiveConnections
看一下sensor 的activate
这里如果是硬件的sensor,HardwareSensor
status_t HardwareSensor::activate(void* ident, bool enabled) { return mSensorDevice.activate(ident, mSensor.getHandle(), enabled); } status_t SensorDevice::activate(void* ident, int handle, int enabled) { if (!mSensorDevice) return NO_INIT; status_t err(NO_ERROR); bool actuateHardware = false; Info& info( mActivationCount.editValueFor(handle) ); .... if (actuateHardware) { ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w"); err = mSensorDevice->activate(mSensorDevice, handle, enabled);//调用到相应的驱动 if (enabled) { ALOGE_IF(err, "Error activating sensor %d (%s)", handle, strerror(-err)); if (err == 0) { BatteryService::getInstance().enableSensor(handle); } } else { if (err == 0) { BatteryService::getInstance().disableSensor(handle); } } } { // scope for the lock Mutex::Autolock _l(mLock); nsecs_t ns = info.selectDelay(); mSensorDevice->setDelay(mSensorDevice, handle, ns); } return err; }
到这里,sensor注册就已经完成了,其中主要是使能了sensor,并启动了数据接收线程,这样应用就可以接收到数据了。