【安卓Sensor框架-1】SensorService 的啟動流程

內核啟動后,首個用戶空間進程init(pid=1)解析init.rc配置文件,啟動關鍵服務(如Zygote和ServiceManager)。
Zygote服務配置為/system/bin/app_process --zygote --start-system-server,后續用于孵化Java進程。Zygote進程通過fork()生成SystemServer進程,并執行com.android.server.SystemServer的main()方法

SystemServer作為Java框架層核心,負責啟動所有系統服務,這些服務就包含有SensorService

所以,SensorService的是跑在系統進程中。整個android sensor模塊的核心是SensorService,應用通過SensorManager與其交互,SensorService管理著sensor的所有行為,包括開關sensor【注冊傳感器】,上報sensor數據給到應用。

接下來,看下sensorservice 的啟動流程

/android-14.0.0_r21/xref/frameworks/base/services/java/com/android/server/SystemServer.java

1351          t.traceBegin("StartSensorService");
// 啟動 SensorService
1352          mSystemServiceManager.startService(SensorService.class);
1353          t.traceEnd();
1354          t.traceEnd(); // startBootstrapServices
1355      }

SystemServiceManager 會通過反射的方法去創建 SensorService 對象,然后回調 onStart 方法

frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

public <T extends SystemService> T startService(Class<T> serviceClass) {try {final String name = serviceClass.getName();Slog.i(TAG, "Starting " + name);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);// Create the service.if (!SystemService.class.isAssignableFrom(serviceClass)) {throw new RuntimeException("Failed to create " + name+ ": service must extend " + SystemService.class.getName());}final T service;try {Constructor<T> constructor = serviceClass.getConstructor(Context.class);// 創建 SensorService 對象service = constructor.newInstance(mContext);} catch (InstantiationException ex) {throw new RuntimeException("Failed to create service " + name+ ": service could not be instantiated", ex);} catch (IllegalAccessException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (NoSuchMethodException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (InvocationTargetException ex) {throw new RuntimeException("Failed to create service " + name+ ": service constructor threw an exception", ex);}startService(service);return service;} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}}@android.ravenwood.annotation.RavenwoodKeeppublic void startService(@NonNull final SystemService service) {// Check if already startedString className = service.getClass().getName();if (mServiceClassnames.contains(className)) {Slog.i(TAG, "Not starting an already started service " + className);return;}mServiceClassnames.add(className);// Register it.mServices.add(service);// Start it.long time = SystemClock.elapsedRealtime();try {// 執行SensorService 的onstart 方法service.onStart();} catch (RuntimeException ex) {throw new RuntimeException("Failed to start service " + service.getClass().getName()+ ": onStart threw an exception", ex);}warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");}

創建 SensorService 對象

/frameworks/base/services/core/java/com/android/server/sensors/SensorService.java

66      public SensorService(Context ctx) {
67          super(ctx);
68          synchronized (mLock) {
69              mSensorServiceStart = SystemServerInitThreadPool.submit(() -> {
70                  TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
71                  traceLog.traceBegin(START_NATIVE_SENSOR_SERVICE);
// 調用native層的方法:startSensorServiceNative
72                  long ptr = startSensorServiceNative(new ProximityListenerDelegate());
73                  synchronized (mLock) {
74                      mPtr = ptr;
75                  }
76                  traceLog.traceEnd();
77              }, START_NATIVE_SENSOR_SERVICE);
78          }
79      }
80  // onstart 方法,將其publish 到servicemanager,系統進程可以通過 SensorManagerInternal.class 獲取到
81      @Override
82      public void onStart() {
83          LocalServices.addService(SensorManagerInternal.class, new LocalService());
84      }

// 調用native層的方法:startSensorServiceNative

/frameworks/base/services/core/jni/com_android_server_sensor_SensorService.cpp

294  static jlong startSensorServiceNative(JNIEnv* env, jclass, jobject listener) {
// 創建 NativeSensorService 對象
295      NativeSensorService* service = new NativeSensorService(env, listener);
296      return reinterpret_cast<jlong>(service);
297  }

// 創建 NativeSensorService 對象

95  NativeSensorService::NativeSensorService(JNIEnv* env, jobject listener)
96        : mProximityActiveListenerDelegate(new ProximityActiveListenerDelegate(env, listener)) {
97      if (base::GetBoolProperty("system_init.startsensorservice", true)) {
98          sp<IServiceManager> sm(defaultServiceManager());
// 創建native 層的 SensorService 對象
99          mService = new SensorService();
// 將其增加到 servicemanager 中
100          sm->addService(String16(SensorService::getServiceName()), mService,
101                         false /* allowIsolated */, IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
102      }
103  }

// SensorService 構造方法

/frameworks/native/services/sensorservice/SensorService.cpp

161  SensorService::SensorService()
// 設置 mSocketBufferSize socket 通信的buffer 的大小
162      : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
163        mWakeLockAcquired(false), mLastReportedProxIsActive(false) {
164      mUidPolicy = new UidPolicy(this);
165      mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
166      mMicSensorPrivacyPolicy = new MicrophonePrivacyPolicy(this);
167  }

// 接著走onfirstref 方法

286  void SensorService::onFirstRef() {
287      ALOGD("nuSensorService starting...");
// 1) SensorDevice構造函數SensorDevice::getInstance()
288      SensorDevice& dev(SensorDevice::getInstance());
289  
290      sHmacGlobalKeyIsValid = initializeHmacKey();
291  
292      if (dev.initCheck() == NO_ERROR) {
293          sensor_t const* list;
294          ssize_t count = dev.getSensorList(&list);
...
306              for (ssize_t i=0 ; i<count ; i++) {
307                  bool useThisSensor = true;
308  
309                  switch (list[i].type) {
310                      case SENSOR_TYPE_ACCELEROMETER:
311                          hasAccel = true;
312                          break;
。。。。
339                  if (useThisSensor) {
340                      if (list[i].type == SENSOR_TYPE_PROXIMITY) {
341                          auto s = std::make_shared<ProximitySensor>(list[i], *this);
342                          const int handle = s->getSensor().getHandle();
// 獲取到hal 層的sensor,這里去注冊sensor
343                          if (registerSensor(std::move(s))) {
344                              mProxSensorHandles.push_back(handle);
345                          }
346                      } else {
347                          registerSensor(std::make_shared<HardwareSensor>(list[i]));
348                      }
349                  }
。。。。。
469              mInitCheck = NO_ERROR;
470              mAckReceiver = new SensorEventAckReceiver(this);
471              mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
// 2)執行 SensorService 的線程方法
472              run("SensorService", PRIORITY_URGENT_DISPLAY);

// SensorDevice構造函數SensorDevice::getInstance()

/frameworks/native/services/sensorservice/SensorDevice.cpp

68  SensorDevice::SensorDevice() {
// 1-1)首先去連接hal service
69      if (!connectHalService()) {
70          return;
71      }
72  
// 1-2)初始化sensor列表:initializeSensorList
73      initializeSensorList();
74  
75      mIsDirectReportSupported = (mHalWrapper->unregisterDirectChannel(-1) != INVALID_OPERATION);
76  }
1-1)首先去連接hal service
138  bool SensorDevice::connectHalService() {
// 創建 AidlSensorHalWrapper 對象
139      std::unique_ptr<ISensorHalWrapper> aidl_wrapper = std::make_unique<AidlSensorHalWrapper>();
// AidlSensorHalWrapper 去連接底層的service
140      if (aidl_wrapper->connect(this)) {
141          mHalWrapper = std::move(aidl_wrapper);
142          return true;
143      }
144  
145      std::unique_ptr<ISensorHalWrapper> hidl_wrapper = std::make_unique<HidlSensorHalWrapper>();
146      if (hidl_wrapper->connect(this)) {
147          mHalWrapper = std::move(hidl_wrapper);
148          return true;
149      }
150  
151      // TODO: check aidl connection;
152      return false;
153  }

// AidlSensorHalWrapper 去連接底層的service,調用 AidlSensorHalWrapper的connect 方法

/frameworks/native/services/sensorservice/AidlSensorHalWrapper.cpp

105  bool AidlSensorHalWrapper::connect(SensorDeviceCallback *callback) {
// allback回調就是 SensorDevice
106      mSensorDeviceCallback = callback;
107      mSensors = nullptr;
108  
// 獲取到aidl 的hal層的sensor 進程service 的名字
109      auto aidlServiceName = std::string() + ISensors::descriptor + "/default";
110      if (AServiceManager_isDeclared(aidlServiceName.c_str())) {
111          if (mSensors != nullptr) {
112              AIBinder_unlinkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
113          }
114  
// 獲取到對應的binder 客戶端對象
115          ndk::SpAIBinder binder(AServiceManager_waitForService(aidlServiceName.c_str()));
116          if (binder.get() != nullptr) {
117              mSensors = ISensors::fromBinder(binder);
// 創建了 mEventQueue  ,與系統進程通信
118              mEventQueue = std::make_unique<AidlMessageQueue<
119                      Event, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
120                                                     /*configureEventFlagWord=*/true);
121  
122              mWakeLockQueue = std::make_unique<AidlMessageQueue<
123                      int32_t, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
124                                                       /*configureEventFlagWord=*/true);
125              if (mEventQueueFlag != nullptr) {
126                  EventFlag::deleteEventFlag(&mEventQueueFlag);
127              }
128              EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
129              if (mWakeLockQueueFlag != nullptr) {
130                  EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
131              }
132              EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakeLockQueueFlag);
133  
134              CHECK(mEventQueue != nullptr && mEventQueueFlag != nullptr &&
135                    mWakeLockQueue != nullptr && mWakeLockQueueFlag != nullptr);
136  
// 創建callback,mSensorDeviceCallback為 SensorDevice
137              mCallback = ndk::SharedRefBase::make<AidlSensorsCallback>(mSensorDeviceCallback);
// binder 通信去初始化,并設置會回調 SensorDevice;這里把 mEventQueue  的 dupeDesc給到了服務器端
138              mSensors->initialize(mEventQueue->dupeDesc(), mWakeLockQueue->dupeDesc(), mCallback);
139  
140              AIBinder_linkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
141          } else {
142              ALOGE("Could not connect to declared sensors AIDL HAL");
143          }
144      }
145  
146      return mSensors != nullptr;
147  }

// binder 通信去初始化,并設置會回調 SensorDevice

對應服務器端為如下, 在init 進程的時候會去創建hal service:

/hardware/interfaces/sensors/aidl/multihal/service.cpp

24  int main() {
25      ABinderProcess_setThreadPoolMaxThreadCount(0);
26  
27      // Make a default multihal sensors service
// 創建了 HalProxyAidl 對象
28      auto halProxy = ndk::SharedRefBase::make<HalProxyAidl>main();
29      const std::string halProxyName = std::string() + HalProxyAidl::descriptor + "/default";
// 并將其保存到了 servicemanager
30      binder_status_t status =
31              AServiceManager_addService(halProxy->asBinder().get(), halProxyName.c_str());
32      CHECK_EQ(status, STATUS_OK);
33  
34      ABinderProcess_joinThreadPool();
35      return EXIT_FAILURE;  // should not reach
36  }

// 創建了 HalProxyAidl 對象,主要調用父類的構造函數:
/hardware/interfaces/sensors/common/default/2.X/multihal/HalProxy.cpp

84  HalProxy::HalProxy() {
85      static const std::string kMultiHalConfigFiles[] = {"/vendor/etc/sensors/hals.conf",
86                                                         "/odm/etc/sensors/hals.conf"};
87      for (const std::string& configFile : kMultiHalConfigFiles) {
// 執行方法 initializeSubHalListFromConfigFile
88          initializeSubHalListFromConfigFile(configFile.c_str());
89      }
90      init();
91  }

// 執行方法 initializeSubHalListFromConfigFile

438  void HalProxy::initializeSubHalListFromConfigFile(const char* configFileName) {
439      std::ifstream subHalConfigStream(configFileName);
440      if (!subHalConfigStream) {
441          ALOGE("Failed to load subHal config file: %s", configFileName);
442      } else {
443          std::string subHalLibraryFile;
444          while (subHalConfigStream >> subHalLibraryFile) {
// 打開so 庫:getHandleForSubHalSharedObject
445              void* handle = getHandleForSubHalSharedObject(subHalLibraryFile);
。。。。
463                  } else {
// 找到 so的 對應的sensorsHalGetSubHal_2_1方法【這里能找到】
464                      SensorsHalGetSubHalV2_1Func* getSubHalV2_1Ptr =
465                              (SensorsHalGetSubHalV2_1Func*)dlsym(handle, "sensorsHalGetSubHal_2_1");
466  
467                      if (getSubHalV2_1Ptr == nullptr) {
468                          ALOGE("Failed to locate sensorsHalGetSubHal function for library: %s",
469                                subHalLibraryFile.c_str());
470                      } else {
471                          std::function<SensorsHalGetSubHalV2_1Func> sensorsHalGetSubHal_2_1 =
472                                  *getSubHalV2_1Ptr;
473                          uint32_t version;
// 調用 sensorsHalGetSubHal_2_1 方法,返回hal層接口
474                          ISensorsSubHalV2_1* subHal = sensorsHalGetSubHal_2_1(&version);
475                          if (version != SUB_HAL_2_1_VERSION) {
476                              ALOGE("SubHal version was not 2.1 for library: %s",
477                                    subHalLibraryFile.c_str());
478                          } else {
479                              ALOGV("Loaded SubHal from library: %s", subHalLibraryFile.c_str());
// j將hal層接口保存到 mSubHalList
480                              mSubHalList.push_back(std::make_unique<SubHalWrapperV2_1>(subHal));
481                          }
482                      }
483                  }

// 打開so 庫:getHandleForSubHalSharedObject

510  void* HalProxy::getHandleForSubHalSharedObject(const std::string& filename) {
511      static const std::string kSubHalShareObjectLocations[] = {
512              "",  // Default locations will be searched
513  #ifdef __LP64__
514              "/vendor/lib64/hw/", "/odm/lib64/hw/"
515  #else
516              "/vendor/lib/hw/", "/odm/lib/hw/"
517  #endif
518      };
519  
520      for (const std::string& dir : kSubHalShareObjectLocations) {
521          void* handle = dlopen((dir + filename).c_str(), RTLD_NOW);
522          if (handle != nullptr) {
523              return handle;
524          }
525      }
526      return nullptr;
527  }

// 接著執行init 方法,獲取到sensors

529  void HalProxy::init() {
530      initializeSensorList();
531  }
489  void HalProxy::initializeSensorList() {
490      for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
// 下列方法會調用到 hal 層去獲取到 sensors
491          auto result = mSubHalList[subHalIndex]->getSensorsList([&](const auto& list) {
492              for (SensorInfo sensor : list) {
493                  if (!subHalIndexIsClear(sensor.sensorHandle)) {
494                      ALOGE("SubHal sensorHandle's first byte was not 0");
495                  } else {
496                      ALOGV("Loaded sensor: %s", sensor.name.c_str());
497                      sensor.sensorHandle = setSubHalIndex(sensor.sensorHandle, subHalIndex);
498                      setDirectChannelFlags(&sensor, mSubHalList[subHalIndex]);
499                      mSensors[sensor.sensorHandle] = sensor;
500                  }
501              }
502          });

=======

// 調用 initialize 方法
/hardware/interfaces/sensors/aidl/default/multihal/HalProxyAidl.cpp

162  ScopedAStatus HalProxyAidl::initialize(
163      const MQDescriptor<::aidl::android::hardware::sensors::Event,
164                         SynchronizedReadWrite> &in_eventQueueDescriptor,
165      const MQDescriptor<int32_t, SynchronizedReadWrite> &in_wakeLockDescriptor,
166      const std::shared_ptr<ISensorsCallback> &in_sensorsCallback) {
167    ::android::sp<::android::hardware::sensors::V2_1::implementation::
168                      ISensorsCallbackWrapperBase>
// 依據callback 創建了 ISensorsCallbackWrapperAidl
169        dynamicCallback = new ISensorsCallbackWrapperAidl(in_sensorsCallback);
170  
// 通過客戶端給到的 in_eventQueueDescriptor,創建 aidlEventQueue 
171    auto aidlEventQueue = std::make_unique<::android::AidlMessageQueue<
172        ::aidl::android::hardware::sensors::Event, SynchronizedReadWrite>>(
173        in_eventQueueDescriptor, true /* resetPointers */);
// 同樣創建 eventQueue  
174    std::unique_ptr<::android::hardware::sensors::V2_1::implementation::
175                        EventMessageQueueWrapperBase>
176        eventQueue =
177            std::make_unique<EventMessageQueueWrapperAidl>(aidlEventQueue);
178  
179    auto aidlWakeLockQueue = std::make_unique<
180        ::android::AidlMessageQueue<int32_t, SynchronizedReadWrite>>(
181        in_wakeLockDescriptor, true /* resetPointers */);
182    std::unique_ptr<::android::hardware::sensors::V2_1::implementation::
183                        WakeLockMessageQueueWrapperBase>
184        wakeLockQueue =
185            std::make_unique<WakeLockMessageQueueWrapperAidl>(aidlWakeLockQueue);
186  
// 調用父類的 initializeCommon 方法
187    return resultToAStatus(
188        initializeCommon(eventQueue, wakeLockQueue, dynamicCallback));
189  }

// 調用父類的 initializeCommon 方法

/hardware/interfaces/sensors/common/default/2.X/multihal/HalProxy.cpp

213  Return<Result> HalProxy::initializeCommon(
214          std::unique_ptr<EventMessageQueueWrapperBase>& eventQueue,
215          std::unique_ptr<WakeLockMessageQueueWrapperBase>& wakeLockQueue,
216          const sp<ISensorsCallbackWrapperBase>& sensorsCallback) {
217      Result result = Result::OK;
218  
219      stopThreads();
220      resetSharedWakelock();
221  
222      // So that the pending write events queue can be cleared safely and when we start threads
223      // again we do not get new events until after initialize resets the subhals.
224      disableAllSensors();
225  
226      // Clears the queue if any events were pending write before.
227      mPendingWriteEventsQueue = std::queue<std::pair<std::vector<V2_1::Event>, size_t>>();
228      mSizePendingWriteEventsQueue = 0;
229  
230      // Clears previously connected dynamic sensors
231      mDynamicSensors.clear();
232  
233      mDynamicSensorsCallback = sensorsCallback;
234  
。。。。
260      mPendingWritesThread = std::thread(startPendingWritesThread, this);
261      mWakelockThread = std::thread(startWakelockThread, this);
262  
// 下列流程也會去初始化 hal層,mSubHalList 是在構造方法中設置了
263      for (size_t i = 0; i < mSubHalList.size(); i++) {
264          Result currRes = mSubHalList[i]->initialize(this, this, i);
265          if (currRes != Result::OK) {
266              result = currRes;
267              ALOGE("Subhal '%s' failed to initialize with reason %" PRId32 ".",
268                    mSubHalList[i]->getName().c_str(), static_cast<int32_t>(currRes));
269          }
270      }
271  
272      mCurrentOperationMode = OperationMode::NORMAL;
273  
274      return result;
275  }

// 1-2)初始化sensor列表:initializeSensorList
/frameworks/native/services/sensorservice/SensorDevice.cpp

78  void SensorDevice::initializeSensorList() {
79      if (mHalWrapper == nullptr) {
80          return;
81      }
82  
// hal 層獲取到sensors
83      auto list = mHalWrapper->getSensorsList();
84      const size_t count = list.size();
85  
86      mActivationCount.setCapacity(count);
87      Info model;
88      for (size_t i = 0; i < count; i++) {
89          sensor_t sensor = list[i];
// 將其保存到 mSensorList
124          mSensorList.push_back(sensor);
2)執行 SensorService 的線程方法
1040  bool SensorService::threadLoop() {
1041      ALOGD("nuSensorService thread starting...");
1042  
1043      // each virtual sensor could generate an event per "real" event, that's why we need to size
1044      // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
1045      // aggressive, but guaranteed to be enough.
1046      const size_t vcount = mSensors.getVirtualSensors().size();
1047      const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
1048      const size_t numEventMax = minBufferSize / (1 + vcount);
1049  
1050      SensorDevice& device(SensorDevice::getInstance());
1051  
1052      const int halVersion = device.getHalDeviceVersion();
1053      do {
// 調用 SensorDevice 監聽 sensor數據
1054          ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
1055          if (count < 0) {
1056              if(count == DEAD_OBJECT && device.isReconnecting()) {
。。。
1172          const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
。。。
// 遍歷所有的connection,去通知到應用客戶端
1235          for (const sp<SensorEventConnection>& connection : activeConnections) {
1236              connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
1237                      mMapFlushEventsToConnections);
1238              needsWakeLock |= connection->needsWakeLock();

// 調用 SensorDevice 監聽 sensor數據

/frameworks/native/services/sensorservice/SensorDevice.cpp

351  ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
352      if (mHalWrapper == nullptr) return NO_INIT;
353  
354      ssize_t eventsRead = 0;
// aidlhal 是為true 的
355      if (mHalWrapper->supportsMessageQueues()) {
// 調用 的pollFmq 
356          eventsRead = mHalWrapper->pollFmq(buffer, count);
357      } else if (mHalWrapper->supportsPolling()) {
358          eventsRead = mHalWrapper->poll(buffer, count);
359      } else {
360          ALOGE("Must support polling or FMQ");
361          eventsRead = -1;
362      }
363  
364      if (eventsRead > 0) {

/frameworks/native/services/sensorservice/AidlSensorHalWrapper.cpp

160  ssize_t AidlSensorHalWrapper::pollFmq(sensors_event_t *buffer, size_t maxNumEventsToRead) {
161      ssize_t eventsRead = 0;
162      size_t availableEvents = mEventQueue->availableToRead();
163  
164      if (availableEvents == 0) {
165          uint32_t eventFlagState = 0;
166  
167          // Wait for events to become available. This is necessary so that the Event FMQ's read() is
168          // able to be called with the correct number of events to read. If the specified number of
169          // events is not available, then read() would return no events, possibly introducing
170          // additional latency in delivering events to applications.
// 等待數據通過 mEventQueueFlag
171          if (mEventQueueFlag != nullptr) {
172              mEventQueueFlag->wait(asBaseType(ISensors::EVENT_QUEUE_FLAG_BITS_READ_AND_PROCESS) |
173                                            asBaseType(INTERNAL_WAKE),
174                                    &eventFlagState);
175          }
176          availableEvents = mEventQueue->availableToRead();

// 對應的 是在connect 方法中,去連接hal 層,也給到了對應的服務器端:

EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);

所以服務器端觸發響應的流程為:

/hardware/interfaces/sensors/common/default/2.X/multihal/HalProxy.cpp

661  void HalProxy::postEventsToMessageQueue(const std::vector<Event>& events, size_t numWakeupEvents,
662                                          V2_0::implementation::ScopedWakelock wakelock) {
663      size_t numToWrite = 0;
664      std::lock_guard<std::mutex> lock(mEventQueueWriteMutex);
665      if (wakelock.isLocked()) {
666          incrementRefCountAndMaybeAcquireWakelock(numWakeupEvents);
667      }
668      if (mPendingWriteEventsQueue.empty()) {
669          numToWrite = std::min(events.size(), mEventQueue->availableToWrite());
670          if (numToWrite > 0) {
// 這里去寫入參數,并喚醒
671              if (mEventQueue->write(events.data(), numToWrite)) {
672                  // TODO(b/143302327): While loop if mEventQueue->avaiableToWrite > 0 to possibly fit
673                  // in more writes immediately
674                  mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS));
675              } else {
676                  numToWrite = 0;
677              }
678          }
679      }
680      size_t numLeft = events.size() - numToWrite;
681      if (numToWrite < events.size() &&
682          mSizePendingWriteEventsQueue + numLeft <= kMaxSizePendingWriteEventsQueue) {
683          std::vector<Event> eventsLeft(events.begin() + numToWrite, events.end());
684          mPendingWriteEventsQueue.push({eventsLeft, numWakeupEvents});
685          mSizePendingWriteEventsQueue += numLeft;
686          mMostEventsObservedPendingWriteEventsQueue =
687                  std::max(mMostEventsObservedPendingWriteEventsQueue, mSizePendingWriteEventsQueue);
688          mEventQueueWriteCV.notify_one();
689      }
690  }

=設置callback 的流程=
/hardware/interfaces/sensors/common/default/2.X/multihal/HalProxy.cpp

438  void HalProxy::initializeSubHalListFromConfigFile(const char* configFileName) {
。。。
478                          } else {
479                              ALOGV("Loaded SubHal from library: %s", subHalLibraryFile.c_str());
// // 創建了 SubHalWrapperV2_1 做為代理類
480                              mSubHalList.push_back(std::make_unique<SubHalWrapperV2_1>(subHal));

// 然后再調用 initializeCommon去初始化 initialize

213  Return<Result> HalProxy::initializeCommon(
214          std::unique_ptr<EventMessageQueueWrapperBase>& eventQueue,
215          std::unique_ptr<WakeLockMessageQueueWrapperBase>& wakeLockQueue,
216          const sp<ISensorsCallbackWrapperBase>& sensorsCallback) {
。。。
263      for (size_t i = 0; i < mSubHalList.size(); i++) {
// 回調為this
264          Result currRes = mSubHalList[i]->initialize(this, this, i);

// SubHalWrapperV2_1 的初始化

/hardware/interfaces/sensors/common/default/2.X/multihal/include/SubHalWrapper.h

// 繼承了 SubHalWrapperBase 的方法
161  class SubHalWrapperV2_1 : public SubHalWrapperBase<V2_1::implementation::ISensorsSubHal> {
162    public:
163      SubHalWrapperV2_1(V2_1::implementation::ISensorsSubHal* subHal) : SubHalWrapperBase(subHal) {}
175  
176      Return<Result> initialize(V2_0::implementation::ISubHalCallback* callback,
177                                V2_0::implementation::IScopedWakelockRefCounter* refCounter,
178                                int32_t subHalIndex) override {
// callback為 HalProxy
179          return mSubHal->initialize(
180                  new V2_0::implementation::HalProxyCallbackV2_1(callback, refCounter, subHalIndex));
181      }
182  };

// 由于 繼承了 SubHalWrapperBase 的方法,所以會調用到 HalProxy::postEventsToMessageQueue 方法

/hardware/interfaces/sensors/common/default/2.X/multihal/HalProxyCallback.cpp

41  void HalProxyCallbackBase::postEvents(const std::vector<V2_1::Event>& events,
42                                        ScopedWakelock wakelock) {
43      if (events.empty() || !mCallback->areThreadsRunning()) return;
44      size_t numWakeupEvents;
45      std::vector<V2_1::Event> processedEvents = processEvents(events, &numWakeupEvents);
46      if (numWakeupEvents > 0) {
47          ALOG_ASSERT(wakelock.isLocked(),
48                      "Wakeup events posted while wakelock unlocked for subhal"
49                      " w/ index %" PRId32 ".",
50                      mSubHalIndex);
51      } else {
52          ALOG_ASSERT(!wakelock.isLocked(),
53                      "No Wakeup events posted but wakelock locked for subhal"
54                      " w/ index %" PRId32 ".",
55                      mSubHalIndex);
56      }
57      mCallback->postEventsToMessageQueue(processedEvents, numWakeupEvents, std::move(wakelock));
58  }

callback 的流程是hal層的傳感器參數回調給系統進程中,在后文的博文 【sensor 事件上報流程】中有解析。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/912272.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/912272.shtml
英文地址,請注明出處:http://en.pswp.cn/news/912272.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

centos網卡綁定參考

同事整理分享&#xff1a; 1. 加載 Bonding 模塊 modprobe bonding 獲取網卡名稱 ip a 找到接了網線的網卡名稱&#xff0c;記下。 3. 配置物理網卡 創建并編輯 /etc/sysconfig/network-scripts/ifcfg-ens36&#xff08;ifcfg-后面的內容根據上面找到的具體網卡名稱決定&#…

mbedtls ssl handshake error,res:-0x2700

用LinkSDK.c連接第三方云平臺出現現象 解決方案&#xff1a; 在_tls_network_establish函數中加入 mbedtls_ssl_conf_authmode(&adapter_handle->mbedtls.ssl_config, MBEDTLS_SSL_VERIFY_NONE);原因解釋&#xff1a;用連接方式是不用證書認證/跳過服務端認證。

Spring Security 的方法級權限控制是如何利用 AOP 的?

Spring Security 的方法級權限控制是 AOP 技術在實際應用中一個極其強大的應用典范。它允許我們以聲明式的方式保護業務方法&#xff0c;將安全規則與業務邏輯徹底解耦。 核心思想&#xff1a;權限檢查的“門衛” 你可以把 AOP 在方法級安全中的作用想象成一個盡職盡責的“門…

一鍵內網穿透,無需域名和服務器,自動https訪問

cloudflare能將內網web轉為外網可訪問的地址。&#xff08;這和apiSQL有點類似&#xff0c;apiSQ可以將內網數據庫輕松轉換為外網的API&#xff0c;并且還支持代理內網已有API&#xff0c;增強安全增加API Key&#xff0c;以https訪問等等&#xff09; 但Cloudfalre tunnel這個…

Sentinel(二):Sentinel流量控制

一、Sentinel 流控規則基本介紹 1、Snetinel 流控規則配置方式 Sentinel 支持可視化的流控規則配置&#xff0c;使用非常簡單&#xff1b;可以在監控服務下的“簇點鏈路” 或 “流控規則” 中 給指定的請求資源配置流控規則&#xff1b;一般推薦在 “簇點鏈路” 中配置流控規則…

支持PY普冉系列單片機調試工具PY32linK仿真器

PY32 Link是專為 ?PY32系列ARM-Cortex內核單片機?&#xff08;如PY32F002A/030/071/040/403等&#xff09;設計的仿真器&#xff0c;支持全系列芯片的?調試和仿真?功能。?開發環境兼容性?支持主流IDE&#xff1a;?Keil MDK? 和 ?IAR Embedded Workbench?&#xff0c;…

深入解析Python多服務器監控告警系統:從原理到生產部署

深入解析Python多服務器監控告警系統&#xff1a;從原理到生產部署 整體架構圖 核心設計思想 無代理監控&#xff1a;通過SSH直接獲取數據&#xff0c;無需在目標服務器安裝代理故障隔離&#xff1a;單臺服務器故障不影響整體監控多級檢測&#xff1a;網絡層→資源層→服務層層…

JUC:10.線程、monitor管程、鎖對象之間在synchronized加鎖的流程(未完)

一、monitor管程工作原理&#xff1a; 首先&#xff0c;synchronized是一個對象鎖&#xff0c;當線程運行到某個臨界區&#xff0c;這個臨界區使用synchronized對對象obj進行了上鎖&#xff0c;此時底層發生了什么&#xff1f; 1.當synchronized對obj上鎖后&#xff0c;synch…

Elasticsearch(ES)分頁

Elasticsearch&#xff08;簡稱 ES&#xff09;本身不適合傳統意義上的“深分頁”&#xff0c;但提供了多種分頁方式&#xff0c;每種適用不同場景。我們來詳細講解&#xff1a; 一、基本分頁&#xff08;from size&#xff09; 最常用的分頁方式&#xff0c;類似 SQL 的 LIM…

原生微信小程序:用 `setData` 正確修改數組中的對象項狀態(附實戰技巧)

&#x1f4cc; 背景介紹 在微信小程序開發中&#xff0c;我們經常需要修改數組中某個對象的某個字段&#xff0c;比如&#xff1a; 列表中的某一項展開/收起多選狀態切換數據列表中的臨時標記等 一個常見的場景是&#xff1a; lists: [{ show: true }, { show: true }, { s…

Oracle 臨時表空間相關操作

一、臨時表空間概述 臨時表空間&#xff08;Temporary Tablespace&#xff09;是Oracle數據庫中用于存儲臨時數據的特殊存儲區域&#xff0c;其數據在會話結束或事務提交后自動清除&#xff0c;重啟數據庫后徹底消失。主要用途包括&#xff1a; 存儲排序操作&#xff08;如OR…

從靜態到動態:Web渲染模式的演進和突破

渲染模式有好多種&#xff0c;了解下web的各種渲染模式&#xff0c;對技術選型有很大的參考作用。 一、靜態HTML時代 早期&#xff08;1990 - 1995年&#xff09;網頁開發完全依賴手工編寫HTML&#xff08;HyperText Markup Language&#xff09;和CSS&#xff08;層疊樣式表…

Flask(六) 數據庫操作SQLAlchemy

文章目錄 一、準備工作二、最小化可運行示例? 補充延遲綁定方式&#xff08;推薦方式&#xff09; 三、數據庫基本操作&#xff08;增刪改查&#xff09;1. 插入數據&#xff08;增&#xff09;2. 查詢數據&#xff08;查&#xff09;3. 更新數據&#xff08;改&#xff09;4.…

PYTHON從入門到實踐7-獲取用戶輸入與while循環

# 【1】獲取用戶輸入 # 【2】python數據類型的轉換 input_res input("請輸入一個數字\n") if int(input_res) % 10 0:print("你輸入的數是10的倍數") else:print("你輸入的數不是10的倍數") # 【3】while循環&#xff0c;適合不知道循環多少次…

學習筆記(C++篇)—— Day 8

1.STL簡介 STL(standard template libaray-標準模板庫)&#xff1a;是C標準庫的重要組成部分&#xff0c;不僅是一個可復用的組件庫&#xff0c;而且是一個包羅數據結構與算法的軟件框架。 2.STL的六大組件 先這樣&#xff0c;下一部分是string的內容&#xff0c;內容比較多&a…

ant+Jmeter+jenkins接口自動化,如何實現把執行失敗的接口信息單獨發郵件?

B站講的最好的自動化測試教程&#xff0c;工具框架附項目實戰一套速通&#xff0c;零基礎完全輕松掌握&#xff01;自動化測試課程、web/app/接口 實現AntJMeterJenkins接口自動化失敗接口郵件通知方案 要實現只發送執行失敗的接口信息郵件通知&#xff0c;可以通過以下步驟實…

惡意Python包“psslib“實施拼寫錯誤攻擊,可強制關閉Windows系統

Socket威脅研究團隊發現一個名為psslib的惡意Python包&#xff0c;該軟件包偽裝成提供密碼安全功能&#xff0c;實則會突然關閉Windows系統。這個由化名umaraq的威脅行為者開發的軟件包&#xff0c;是對知名密碼哈希工具庫passlib的拼寫錯誤仿冒&#xff08;typosquatting&…

云原生灰度方案對比:服務網格灰度(Istio ) 與 K8s Ingress 灰度(Nginx Ingress )

服務網格灰度與 Kubernetes Ingress 灰度是云原生環境下兩種主流的灰度發布方案&#xff0c;它們在架構定位、實現方式和適用場景上存在顯著差異。以下從多個維度對比分析&#xff0c;并給出選型建議&#xff1a; 一、核心區別對比 維度服務網格灰度&#xff08;以 Istio 為例…

科技如何影響我們的生活?

科技已成為我們生活中不可或缺的一部分&#xff0c;徹底改變了我們工作、溝通和生活的方式。從智能手機到智能家居&#xff0c;科技已滲透到我們生活的每個角落。無論是用手機鬧鐘開啟新的一天&#xff0c;通過 Alexa 開關燈光&#xff0c;還是打開 Uber 或 Lyft 打車上班&…

Re--攻防世界-基礎android

Jadx 可以看到有賬號密碼輸入 進入checkPassword函數 分析一下&#xff1a; 對每個字符 pass[len] 進行以下計算 pass[len] (char) (((255 - len) - 100) - pass[len]); 解密腳本 def decrypt_password(): password [] for len in range(12): c (255 - le…