目錄
1.1 SysterServer啟動sensorservice
1.2 android_servers.so 啟動sersorservice
1.3 SensorService instantiate
1.4 SensorService:: onFirstRef
1.1 SysterServer啟動sensorservice
sensorservice通過SystemServer啟動,運作在SystemServer程序,是一個binder服務,通過addService(sensorservice)到ServiceManager
@SystemServer.java
startBootstrapServices();
startCoreServices();
startOtherServices();
private void startBootstrapServices() {
...
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
startSensorService(); //startSensorService
}, START_SENSOR_SERVICE);
}
private static native void startSensorService(); //libandroid_servers.so
1.2 android_servers.so 啟動sersorservice
startSensorService是使用的libandroid_servers.so,這個庫是在SystemServer.run()裡面加載
@frameworks/base/services/core/jni/com_android_server_SystemServer.cpp
static const JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "startSensorService", "()V", (void*) android_server_SystemServer_startSensorService },
{ "startHidlServices", "()V", (void*) android_server_SystemServer_startHidlServices },
};
static void android_server_SystemServer_startSensorService(JNIEnv* /* env */, jobject /* clazz */) {
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
SensorService::instantiate();
}
}
1.3 SensorService instantiate
SensorService繼承BinderService,執行BinderService::instantiate,也就是addService到ServiceManager
@SensorService.h
class SensorService :
public BinderService<SensorService>,
public BnSensorServer,
protected Thread
{
@frameworks/native/include/binder/BinderService.h
class BinderService
{
public:
static status_t publish(bool allowIsolated = false) {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}
static void publishAndJoinThreadPool(bool allowIsolated = false) {
publish(allowIsolated);
joinThreadPool();
}
static void instantiate() { publish(); }
static status_t shutdown() { return NO_ERROR; }
//代碼裡SERVICE為sensorservice,也可以通過service list檢視
@/frameworks/native/services/sensorservice/SensorService.h
static char const* getServiceName() ANDROID_API { return "sensorservice"; }
SensorService最終會繼承到RefBase,就會執行自己的onFirstRef方法
1.4 SensorService:: onFirstRef
//SensorService內建Binder也是一個Thread,是以會執行 onFirstRef初始化,和執行threadLoop處理SensorEvent
@frameworks/native/services/sensorservice/SensorService.cpp
void SensorService::onFirstRef() {
SensorDevice& dev(SensorDevice::getInstance()); //1 擷取SensorDevice對象
sHmacGlobalKeyIsValid = initializeHmacKey();
if (dev.initCheck() == NO_ERROR) {
sensor_t const* list;
ssize_t count = dev.getSensorList(&list); //2 擷取晶片商在Hal層初始化好的SensorList,并傳回sensor的數目
if (count > 0) {
ssize_t orientationIndex = -1;
for (ssize_t i=0 ; i<count ; i++) {
bool useThisSensor=true;
...
if (useThisSensor) {
registerSensor( new HardwareSensor(list[i]) ); //3 sensor注冊
}
}
SensorFusion::getInstance();
...
if (hasAccel && hasGyro) {
bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
bool needGameRotationVector =
(virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
}
...
mAckReceiver = new SensorEventAckReceiver(this); //4 啟動服務
mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
run("SensorService", PRIORITY_URGENT_DISPLAY);
}
}
}
new 了幾個對象後,調用 SensorEventAckReceiver:run()以及 SensorService:run(),進入它們各自實作其父類 Thread 的
threadLoop 方法裡邊,先看 SensorEventAckReceiver:threadLoop(),
bool SensorService::threadLoop() {
SensorDevice& device(SensorDevice::getInstance());
const int halVersion = device.getHalDeviceVersion();
do {
ssize_t count = device.poll(mSensorEventBuffer, numEventMax); //device.poll
SortedVector< sp<SensorEventConnection> > activeConnections;
populateActiveConnections(&activeConnections);
// handle virtual sensors
if (count && vcount) {
sensors_event_t const * const event = mSensorEventBuffer;
...
}
//發送事件到用戶端 android_hardware_SensorManager.cpp Receiver
// Send our events to clients. Check the state of wake lock for each client and release the
// lock if none of the clients need it.
bool needsWakeLock = false;
size_t numConnections = activeConnections.size();
for (size_t i=0 ; i < numConnections; ++i) {
if (activeConnections[i] != 0) {
activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
mMapFlushEventsToConnections);
needsWakeLock |= activeConnections[i]->needsWakeLock();
// If the connection has one-shot sensors, it may be cleaned up after first trigger.
// Early check for one-shot sensors.
if (activeConnections[i]->hasOneShotSensors()) {
cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
count);
}
}
}
} while (!Thread::exitPending());
...
}
//Singleton單例模式
class SensorDevice : public Singleton<SensorDevice>, public Dumpable {
//mSensors = Iservice.getservice mSensors就是ISensors
SensorDevice::SensorDevice() : mHidlTransportErrors(20) {
...
}
#include "android/hardware/sensors/1.0/ISensors.h"
@hardware/interfaces/sensors/1.0/ISensors.hal
activate(int32_t sensorHandle, bool enabled) generates (Result result);
@android/hardware/interfaces/sensors/1.0/default/Sensors.cpp
Return<Result> Sensors::activate(
int32_t sensor_handle, bool enabled) {
return ResultFromStatus(
mSensorDevice->activate(
reinterpret_cast<sensors_poll_device_t *>(mSensorDevice),
sensor_handle,
enabled));
}
Sensors::Sensors()
status_t err = OK;
if (UseMultiHal()) {
mSensorModule = ::get_multi_hal_module_info();
} else {
err = hw_get_module( //1
SENSORS_HARDWARE_MODULE_ID,
(hw_module_t const **)&mSensorModule);
}
...
err = sensors_open_1(&mSensorModule->common, &mSensorDevice); //調用sensor.h的sensors_open_1方法打開裝置
}