sensorservice的启动:
1. systemserver.java的run函数:
private void run() {
……
// Initialize native services.
System.loadLibrary("android_servers");
nativeInit();
……
}
Android在启动之后通过Zygote来管理和启动android server,他首先会运行SystemServer.java里面的run函数,这里主要是load android_server.so库,然后调用nativeInit()来启动sensorservice。
2. nativeInit()是本地方法,上层Java调用本地C++方法,需要通过JNI层的转化,在com_android_server_SystemServer.cpp中:
static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the sensor service
SensorService::instantiate();
}
}
/*
* JNI registration.
*/
static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "nativeInit", "()V", (void*) android_server_SystemServer_nativeInit },
};
int register_android_server_SystemServer(JNIEnv* env)
{
return jniRegisterNativeMethods(env, "com/android/server/SystemServer",
gMethods, NELEM(gMethods));
}
首先建立nativeInit()方法对本地方法android_server_SystemServer_nativeInit()的映射,然后jniRegisterNativeMethods注册该方法,在上层调用nativeInit()方法就可以调用本地方法android_server_SystemServer_nativeInit()通过SensorService::instantiate();来实例化sensorservice,主要是向servicemanager注册sensorservice。
static status_t publish(bool allowIsolated = false) {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}
static void instantiate() { publish(); }
addservice()方法主要是完成向servicemanager注册sensorservice服务,原型如下:
virtual status_t addService( const String16& name,
const sp<IBinder>& service,
bool allowIsolated = false) = 0;
其第二个参数也就是new SERVICE()是强引用sp sensorservice,所以会调用到SensorService::onFirstRef(),这样就开始了sensorservice的一系列初始化工作。
3. SensorService::onFirstRef()
void SensorService::onFirstRef()
{
ALOGD("nuSensorService starting...");
SensorDevice& dev(SensorDevice::getInstance());
if (dev.initCheck() == NO_ERROR) {
sensor_t const* list;
ssize_t count = dev.getSensorList(&list);
if (count > 0) {
ssize_t orientationIndex = -1;
bool hasGyro = false;
uint32_t virtualSensorsNeeds =
(1<<SENSOR_TYPE_GRAVITY) |
(1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
(1<<SENSOR_TYPE_ROTATION_VECTOR);
mLastEventSeen.setCapacity(count);
for (ssize_t i=0 ; i<count ; i++)