SensorService流程分析

本文深入探讨了Android系统的SensorService,从其启动、SensorDevice实例化、传感器设备打开流程、数据传输机制到数据接收和发送的过程,详细解析了SensorService如何管理并传递底层传感器数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SensorService是用来管理底层sensor的服务;
首先来看下它的启动,在SystemServer中的run()中有:

   // Initialize native services.
    System.loadLibrary("android_servers");
    nativeInit();

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
        SensorService::instantiate();
    }

在看下SensorService.cpp中的实现:

SensorService::SensorService()
    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
      mWakeLockAcquired(false)
{
}

void SensorService::onFirstRef()
{
    ALOGD("nuSensorService starting...");
    //1:sensorDevice的实例化
    SensorDevice& dev(SensorDevice::getInstance());

    if (dev.initCheck() == NO_ERROR) {
        sensor_t const* list;
        //拿到硬件的sensor列表
        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++) {
               //注册sensor
                registerSensor( new HardwareSensor(list[i]) );
                switch (list[i].type) {
                    case SENSOR_TYPE_ORIENTATION:
                        orientationIndex = i;
                        break;
                    case SENSOR_TYPE_GYROSCOPE:
                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
                        hasGyro = true;
                        break;
                    case SENSOR_TYPE_GRAVITY:
                    case SENSOR_TYPE_LINEAR_ACCELERATION:
                    case SENSOR_TYPE_ROTATION_VECTOR:
                        virtualSensorsNeeds &= ~(1<<list[i].type);
                        break;
                }
            }

            // it's safe to instantiate the SensorFusion object here
            // (it wants to be instantiated after h/w sensors have been
            // registered)
            const SensorFusion& fusion(SensorFusion::getInstance());

            // build the sensor list returned to users
            mUserSensorList = mSensorList;

            if (hasGyro) {
                Sensor aSensor;

                // Add Android virtual sensors if they're not already
                // available in the HAL

                aSensor = registerVirtualSensor( new RotationVectorSensor() );
                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
                    mUserSensorList.add(aSensor);
                }

                aSensor = registerVirtualSensor( new GravitySensor(list, count) );
                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
                    mUserSensorList.add(aSensor);
                }

                aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
                    mUserSensorList.add(aSensor);
                }

                aSensor = registerVirtualSensor( new OrientationSensor() );
                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
                    // if we are doing our own rotation-vector, also add
                    // the orientation sensor and remove the HAL provided one.
                    mUserSensorList.replaceAt(aSensor, orientationIndex);
                }

                // virtual debugging sensors are not added to mUserSensorList
                registerVirtualSensor( new CorrectedGyroSensor(list, count) );
                registerVirtualSensor( new GyroDriftSensor() );
            }

            // debugging sensor list
            mUserSensorListDebug = mSensorList;

            // Check if the device really supports batching by looking at the FIFO event
            // counts for each sensor.
            bool batchingSupported = false;
            for (int i = 0; i < mSensorList.size(); ++i) {
                if (mSensorList[i].getFifoMaxEventCount() > 0) {
                    batchingSupported = true;
                    break;
                }
            }

            if (batchingSupported) {
                // Increase socket buffer size to a max of 100 KB for batching capabilities.
                mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
            } else {
                mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
            }

            // Compare the socketBufferSize value against the system limits and limit
            // it to maxSystemSocketBufferSize if necessary.
            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
            char line[128];
            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
                line[sizeof(line) - 1] = '\0';
                size_t maxSystemSocketBufferSize;
                sscanf(line, "%zu", &maxSystemSocketBufferSize);
                if (mSocketBufferSize > maxSystemSocketBufferSize) {
                    mSocketBufferSize = maxSystemSocketBufferSize;
                }
            }
            if (fp) {
                fclose(fp);
            }

            mWakeLockAcquired = false;
            mLooper = new Looper(false);
            const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
            mSensorEventBuffer = new sensors_event_t[minBufferSize];
            mSensorEventScratch = new sensors_event_t[minBufferSize];
            mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];

            mAckReceiver = new SensorEventAckReceiver(this);
            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
            mInitCheck = NO_ERROR;
            run("SensorService", PRIORITY_URGENT_DISPLAY);
        }
    }
}

首先看下SensorDevice的实例化:

SensorDevice::SensorDevice()
    :  mSensorDevice(0),
       mSensorModule(0)
{   //1:加载hal层的so
    status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,
            (hw_module_t const**)&mSensorModule);

    ALOGE_IF(err, "couldn't load %s module (%s)",
            SENSORS_HARDWARE_MODULE_ID, strerror(-err));

    if (mSensorModule) {
       //2:打开设备
        err = sensors_open_1(&mSensorModule->common, &mSensorDevice);

        ALOGE_IF(err, "couldn't open device for module %s (%s)",
                SENSORS_HARDWARE_MODULE_ID, strerror(-err));

        if (mSensorDevice) {
            if (mSensorDevice->common.version == SENSORS_DEVICE_API_VERSION_1_1 ||
                mSensorDevice->common.version == SENSORS_DEVICE_API_VERSION_1_2) {
                ALOGE(">>>> WARNING <<< Upgrade sensor HAL to version 1_3");
            }

            sensor_t const* list;
            //3:得到sensor列表
            ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list);
            mActivationCount.setCapacity(count);
            Info model;
            for (size_t i=0 ; i<size_t(count) ; i++) {
                mActivationCount.add(list[i].handle, model);
                //4:激活sensor
                mSensorDevice->activate(
                        reinterpret_cast<struct sensors_poll_device_t *>(mSensorDevice),
                        list[i].handle, 0);
            }
        }
    }
}

再看下sensors_open_1的流程:

static inline int sensors_open_1(const struct hw_module_t* module,
        sensors_poll_device_1_t** device) {
        //调用hal中的open方法
    return module->methods->open(module,
            SENSORS_HARDWARE_POLL, (struct hw_device_t**)device);
}

以hal层的sensors继续分析:

/** Open a new instance of a sensor device using name */
static int open_sensors(const struct hw_module_t* module, const char* id,
                        struct hw_device_t** device)
{
        int status = -EINVAL;
        //先创建一个sensors_poll_context_t
        sensors_poll_context_t *dev = new sensors_poll_context_t();

                id = id;
        memset(&dev->device, 0, sizeof(sensors_poll_device_t));

        dev->device.common.tag = HARDWARE_DEVICE_TAG;
        dev->device.common.version  = 0;
        dev->device.common.module   = const_cast<hw_module_t*>(module);
        dev->device.common.close    = poll__close;
        dev->device.activate        = poll__activate;
        dev->device.setDelay        = poll__setDelay;
        dev->device.poll            = poll__poll;

        *device = &dev->device.common;
        status = 0;

        return status;
}
static int sensors__get_sensors_list(struct sensors_module_t* module,
                                     struct sensor_t const** list) 
{
                module = module;
        //拿到底层硬件sensor支持列表
        *list = sSensorList;        
        return sSensorListNum;
}

static struct hw_module_methods_t sensors_module_methods = {
        //指定open方法为open_sensors
        open: open_sensors
};

最后看下激活sensor的流程:

static int poll__activate(struct sensors_poll_device_t *dev,
        int handle, int enabled) {
    sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
    return ctx->activate(handle, enabled);
}

int sensors_poll_context_t::activate(int handle, int enabled) {
    int err;

    // Orientation requires accelerometer and magnetic sensor
    if (handle == ID_O) {
        mOrientationActive = enabled ? true : false;
        if (!mAccelActive) {
            err = real_activate(ID_A, enabled);
            if (err) return err;
        }
        if (!mMagnetActive) {
            err = real_activate(ID_M, enabled);
            if (err) return err;
        }
    }
    // Keep track of magnetic and accelerometer use from system
    else if (handle == ID_A) {
        mAccelActive = enabled ? true : false;
        // No need to enable or disable if orientation sensor is active as that will handle it
        if (mOrientationActive) return 0;
    }
    else if (handle == ID_M) {
        mMagnetActive = enabled ? true : false;
        // No need to enable or disable if orientation sensor is active as that will handle it
        if (mOrientationActive) return 0;
    }

    return real_activate(handle, enabled);
}

int sensors_poll_context_t::real_activate(int handle, int enabled) {
    int index = handleToDriver(handle);
    if (index < 0) return index;
    int err =  mSensors[index]->enable(handle, enabled);
    if (enabled && !err) {
        const char wakeMessage(WAKE_MESSAGE);
        int result = write(mWritePipeFd, &wakeMessage, 1);
        ALOGE_IF(result<0, "error sending wake message (%s)", strerror(errno));
    }
    return err;
}

如果是AccelerationSensor的类型:对input中对应的节点写1或者0

int AccelerationSensor::enable(int32_t, int en) {

    ALOGD("AccelerationSensor::~enable(0, %d)", en);
    int flags = en ? 1 : 0;
    if (flags != mEnabled) {
        int fd;
        strcpy(&input_sysfs_path[input_sysfs_path_len], "enable");
        fd = open(input_sysfs_path, O_RDWR);
        if (fd >= 0) {
            char buf[2];
            int err;
            buf[1] = 0;
            if (flags) {
                buf[0] = '1';
            } else {
                buf[0] = '0';
            }
            err = write(fd, buf, sizeof(buf));
            close(fd);
            mEnabled = flags;
            //setInitialState();
            return 0;
        }
        return -1;        
    }
    return 0;
}

启动流程到这里基本完毕了;接下来需要再继续看下数据的传输过程,看底层数据是怎么从底层传递到上层的,在SensorService的looper中,会不断的检测是否有数据

bool SensorService::threadLoop()
{
...
    const int halVersion = device.getHalDeviceVersion();
    do {
        //调用底层的poll函数
        ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
        if (count < 0) {
            ALOGE("sensor poll failed (%s)", strerror(-count));
            break;
        }
...
ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
    if (!mSensorDevice) return NO_INIT;
    ssize_t c;
    do {
        c = mSensorDevice->poll(reinterpret_cast<struct sensors_poll_device_t *> (mSensorDevice),
                                buffer, count);
    } while (c == -EINTR);
    return c;
}
static int poll__poll(struct sensors_poll_device_t *dev,
        sensors_event_t* data, int count) {
    sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
    return ctx->pollEvents(data, count);
}

int sensors_poll_context_t::pollEvents(sensors_event_t* data, int count)
{
    int nbEvents = 0;
    int n = 0;

    do {
        // see if we have some leftover from the last poll()
        for (int i=0 ; count && i<numSensorDrivers ; i++) {
            SensorBase* const sensor(mSensors[i]);
            if (sensor == NULL) {
                continue;
            }
            if ((mPollFds[i].revents & POLLIN) || (sensor->hasPendingEvents())) {
                //这里回去读驱动上报的数据
                int nb = sensor->readEvents(data, count);
                if (nb < count) {
                    // no more data for this sensor
                    mPollFds[i].revents = 0;
                }
                count -= nb;
                nbEvents += nb;
                data += nb;
            }
        }

        if (count) {
            // we still have some room, so try to see if we can get
            // some events immediately or just wait if we don't have
            // anything to return
            do {
            n = poll(mPollFds, numFds, nbEvents ? 0 : -1);
            } while (n < 0 && errno == EINTR);
            if (n<0) {
                ALOGE("poll() failed (%s)", strerror(errno));
                return -errno;
            }
            if (mPollFds[wake].revents & POLLIN) {
                char msg;
                int result = read(mPollFds[wake].fd, &msg, 1);
                ALOGE_IF(result<0, "error reading from wake pipe (%s)", strerror(errno));
                ALOGE_IF(msg != WAKE_MESSAGE, "unknown message on wake queue (0x%02x)", int(msg));

                mPollFds[wake].revents = 0;
            }
        }
        // if we have events and space, go read them
    } while (n && count);

    return nbEvents;
}

最后在sensor中读取数据:

int AccelerationSensor::readEvents(sensors_event_t* data, int count)
{
    //ALOGD("AccelerationSensor::~readEvents() %d", count);
    if (count < 1)
        return -EINVAL;

    if (mHasPendingEvent) {
        mHasPendingEvent = false;
        mPendingEvent.timestamp = getTimestamp();
        *data = mPendingEvent;
        return mEnabled ? 1 : 0;
    }
    //首先填充读取数据
    ssize_t n = mInputReader.fill(data_fd);
    if (n < 0)
        return n;

    int numEventReceived = 0;
    input_event const* event;
    //读取数据
    while (count && mInputReader.readEvent(&event)) {

     if(event == NULL)
     {
         ALOGE("llw AccelerationSensor::readEvents()  null pointer!!!" );
     }
     else
     {  
         //解析读到的数据
            int type = event->type;
            if (type == EV_ABS) {
                float value = event->value;
                if (event->code == EVENT_TYPE_ACCEL_X) {
                    mPendingEvent.acceleration.x = value * mResolution;
                } else if (event->code == EVENT_TYPE_ACCEL_Y) {
                    mPendingEvent.acceleration.y = value * mResolution;
                } else if (event->code == EVENT_TYPE_ACCEL_Z) {
                    mPendingEvent.acceleration.z = value * mResolution;
                }
            } else if (type == EV_SYN) {
                mPendingEvent.timestamp = timevalToNano(event->time);
                if (mEnabled) {
                    *data++ = mPendingEvent;
                    count--;
                    numEventReceived++;
                }
            } else {
                ALOGE("AccelerationSensor: unknown event (type=%d, code=%d)",
                        type, event->code);
            }
         }
        mInputReader.next();
    }

    //ALOGD("AccelerationSensor::~readEvents() numEventReceived = %d", numEventReceived);
    return numEventReceived;

}

接收到了数据就要发送出去,在哪里发送呢?还是在SensorService::threadLoop()看下:

for (size_t i=0 ; i < numConnections; ++i) {
            if (activeConnections[i] != 0) {
                //通过activeConnections的sendEvents来发送数据
                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);

继续跟踪:

status_t SensorService::SensorEventConnection::sendEvents(
        sensors_event_t const* buffer, size_t numEvents,
        sensors_event_t* scratch,
        SensorEventConnection const * const * mapFlushEventsToConnections) {
        ...
            // NOTE: ASensorEvent and sensors_event_t are the same type.
    ssize_t size = SensorEventQueue::write(mChannel,
                                    reinterpret_cast<ASensorEvent const*>(scratch), count);
        ...
        }
ssize_t SensorEventQueue::write(const sp<BitTube>& tube,
        ASensorEvent const* events, size_t numEvents) {
    return BitTube::sendObjects(tube, events, numEvents);
}

最终是通过BitTube将数据发送出去
既然数据有发送,必然就会有数据的接收:

<think>好的,用户想了解Android传感器的启动流程,也就是Android传感器初始化的过程。我需要根据提供的引用资料来梳理整个流程。首先,我需要回忆系统级指令的要求,确保回答符合格式,比如行内公式用$...$,独立公式用$$...$$,同时用中文回答,生成相关问题,并在引用处添加标识。 用户的问题是关于Android传感器启动流程的,所以需要结合提供的三个引用内容。引用[1]提到了SystemSensorManager如何通过native方法创建和获取传感器实例,还有getSystemService的调用过程。引用[2]提到SystemServer的init2调用ActivityManagerService.systemReady来启动第一个Activity,这可能和传感器服务的启动时机有关。引用[3]则涉及Android初始化过程中的Actions和触发机制,可能和传感器服务的初始化步骤相关。 首先,我需要整理整个启动流程的步骤。可能从SystemServer启动开始,然后是SensorService的初始化,接着是SystemSensorManager的创建,最后是应用层获取传感器实例的过程。需要结合引用中的各个步骤,比如ContextImpl的getSystemService,SystemSensorManager的native方法调用,以及ActivityManagerService启动后的触发动作。 另外,要注意用户的问题可能关注的是系统启动时传感器服务如何被初始化和加载,以及应用层如何通过getSystemService获取传感器实例。需要分层次说明,从系统服务启动到应用层调用,确保流程清晰。 在生成相关问题的时候,需要考虑用户可能进一步想了解的内容,比如传感器服务的启动顺序、如何添加自定义传感器、初始化失败的原因等。这些问题需要基于已有的引用内容,确保相关性。 最后,检查是否符合所有系统级指令,比如正确的LaTeX格式(虽然这个问题可能不需要数学公式,但如果有的话要处理),引用标识是否正确,结构是否清晰,使用中文等。确保没有遗漏关键步骤,并且逻辑连贯。</think>### Android传感器初始化流程分析 Android传感器系统的初始化流程可分为三个主要阶段: 1. **系统服务初始化阶段** - 在`SystemServer`启动时创建`SensorService`,该服务继承自`SystemService`类,完成硬件抽象层(HAL)的加载和传感器设备枚举 - 通过`init1()`和`init2()`完成服务初始化,其中`init2()`通过`ActivityManagerService.systemReady()`触发主界面启动[^2] 2. **服务注册阶段** - 在`SystemServer`的`startOtherServices()`方法中注册传感器服务: ```java mSystemServiceManager.startService(SensorService.class); ``` - 通过`ServiceManager`将服务注册到Binder框架,完成`SensorManager`与底层驱动的对接 3. **应用层调用阶段** 当应用调用`getSystemService(SENSOR_SERVICE)`时: ```java // ContextImpl.java public Object getSystemService(String name) { return SystemServiceRegistry.getSystemService(this, name); } ``` - 通过`SystemSensorManager`创建代理对象,实际调用`nativeCreate()`与`nativeGetSensorAtIndex()`获取传感器列表[^1] $$传感器数据流公式:\\ S(t) = \int_{t_0}^{t} \sum_{i=1}^{n} w_i \cdot s_i(\tau) d\tau$$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值