Android Sensor (3) -- 服务端SensorService启动

 

目录

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方法打开设备
}

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值