iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 20
0
  • Guide:
    • 介紹 (Overview)
    • 架構 (Architecture)
    • 應用 (Application)
    • 服務 (Service)
    • 硬件抽象層 (HAL)

註冊服務

上一篇講到稍微寫一個小小的傳感器應用程式,
主要就是透過下列的幾個方法可以實作:

mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
Sensor mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mSensorManager.registerListener(xxx);

這段會稍微講解到一點 Android 服務註冊的盤古開天史,
簡單講就是一般我們系統啟動時,
總是有第一隻起來的程序,
就像之前說的,每一個層級和大架構我們都搞清楚後,
在每一層樓的最後一個人結束後,
就會通知下一層樓的第一個人要開始作第一件事,
你可以想成 Boot Loader 啟動 Kernel 後,
Kernel 又啟動了 Android 層的 init.rczygote
這個 init.rc 就是我們所指 Android 樓層的第一個人。

Android 啟動流程我就不多作解釋了,
其實 Sensor 註冊過程和 NFC 相當類似,
也是透過 SystemSensorManager 繼承了 SensorManager
來實現註冊的過程:

frameworks/base/core/java/android/app/SystemServiceRegistry.java

 171 final class SystemServiceRegistry {
 172     private static final String TAG = "SystemServiceRegistry";
... ... 
 182     // Not instantiable.
 183     private SystemServiceRegistry() { }
 184  
 185     static {
... ...
 452         registerService(Context.SENSOR_SERVICE, **SensorManager.class**, 
 453                 new CachedServiceFetcher<SensorManager>() {
 454             @Override            
 455             public **SensorManager** createService(ContextImpl ctx) {
 456                 return new **SystemSensorManager**(ctx.getOuterContext(),
 457                   ctx.mMainThread.getHandler().getLooper());
 458             }});
... ...

而上面我們又看到 SystemSensorManager 是在 SystemServiceRegistery 靜態初始化區塊中,
因此在系統初始階段加載 SystemServiceRegistry 時,
SystemSensorManager 就會被創建,來看一下它的構造函數:

frameworks/base/core/java/android/hardware/SystemSensorManager.java

103     public SystemSensorManager(Context context, Looper mainLooper) {
104         synchronized (sLock) {       
105             if (!sNativeClassInited) {
106                 sNativeClassInited = true;
**//獲取FieldID和MethodID,存gSensorOffsets中.為後續JNI的get/set做準備**
107                 nativeClassInit();   
108             }                        
109         }                            
110                                      
111         mMainLooper = mainLooper;    
112         mTargetSdkLevel = context.getApplicationInfo().targetSdkVersion;
113         mContext = context;
**//創建Native層的SensorManager**
114         mNativeInstance = **nativeCreate**(context.getOpPackageName());
115                                      
116         // initialize the sensor list
**//通過Native層的SensorManager的getSensorList方法,初始化傳感器列表,
//並填充到mFullSensorsList當中.建立sensor和handle之間的映射,存放在mHandleToSensor中**
117         for (int index = 0;; ++index) {
118             Sensor sensor = new Sensor();
**//將Native層的sensor,通過JNI返回到Java層**
119             if (!nativeGetSensorAtIndex(mNativeInstance, sensor, index)) break;
120             mFullSensorsList.add(sensor);
121             mHandleToSensor.put(sensor.getHandle(), sensor);
122         }                            
123     }

調用 nativeCreate 創建 Native 層的 SensorManager
在創建過程中會循環等待 SensorService 被創建,
和它建立 binder 關係。
接著調用 SensorSerivcegetSensorList
來獲取硬件傳感器列表信息:

frameworks/base/core/jni/android_hardware_SensorManager.cpp

145 static jlong                
146 **nativeCreate**                
147 (JNIEnv *env, jclass clazz, jstring opPackageName) 
148 {                           
149     ScopedUtfChars opPackageNameUtf(env, opPackageName);
150     return (jlong) &**SensorManager**::**getInstanceForPackage**(String16(opPackageNameUtf.c_str())); 
151 }

frameworks/native/libs/sensor/SensorManager.cpp

 45 SensorManager& SensorManager::getInstanceForPackage(const String16& packageName) {
 46     waitForSensorService(nullptr); 
 47                                 
 48     Mutex::Autolock _l(sLock);  
 49     SensorManager* sensorManager;  
 50     auto iterator = sPackageInstances.find(packageName);
 51                                 
 52     if (iterator != sPackageInstances.end()) { 
 53         sensorManager = iterator->second;       
 54     } else {                    
 55         String16 opPackageName = packageName;
 56 
... ...
**//創建Native層sensorManager,接著看SensorManager的構造函數**
 79         sensorManager = new SensorManager(opPackageName);
 80                                 
... ...
 88         // Stash the per package sensor manager.
 89         sPackageInstances.insert(std::make_pair(opPackageName, sensorManager));
 90     }                           
 91                                 
 92     return *sensorManager;      
 93 }

frameworks/native/libs/sensor/SensorManager.cpp

 95 SensorManager::SensorManager(const String16& opPackageName)
 96     : mSensorList(0), mOpPackageName(opPackageName), mDirectConnectionHandle(1) {
 97     // okay we're not locked here, but it's not needed during construction
 98     **assertStateLocked**();
 99 }

frameworks/native/libs/sensor/SensorManager.cpp

135 status_t SensorManager::assertStateLocked() {
136     bool initSensorManager = false;
137     if (mSensorServer == NULL) {
138         initSensorManager = true;
139     } else {
140         // Ping binder to check if sensorservice is alive.
141         status_t err = IInterface::asBinder(mSensorServer)->pingBinder();
142         if (err != NO_ERROR) {
143             initSensorManager = true;
144         }
145     }    
146     if (initSensorManager) {
147         **waitForSensorService**(&mSensorServer);
148         LOG_ALWAYS_FATAL_IF(mSensorServer == nullptr, "getService(SensorService) NULL");
149          
... ...

frameworks/native/libs/sensor/SensorManager.cpp

105 status_t SensorManager::waitForSensorService(sp<ISensorServer> *server) {
106     // try for 300 seconds (60*5(getService() tries for 5 seconds)) before giving up ...  
107     sp<ISensorServer> s; 
**//等待获取Native层的SensorService被注册,超时时间300s**
108     const String16 name("sensorservice");
109     for (int i = 0; i < 60; i++) {
110         status_t err = getService(name, &s);
111         switch (err) {            
112             case NAME_NOT_FOUND:  
113                 sleep(1);         
114                 continue;         
115             case NO_ERROR:        
116                 if (server != nullptr) {
117                     *server = s;  
118                 }                 
119                 return NO_ERROR;  
120             default:              
121                 return err;       
122         }                         
123     }                             
124     return TIMED_OUT;             
125 }

再跳回原來的位置:

frameworks/native/libs/sensor/SensorManager.cpp

135 status_t SensorManager::assertStateLocked() {
... ...
**//看看SensorManager有沒有bind成功或是服務死了的後續處理**
150         class DeathObserver : public IBinder::DeathRecipient {
151             SensorManager& mSensorManager; 
152             virtual void binderDied(const wp<IBinder>& who) {
153                 ALOGW("sensorservice died [%p]", who.unsafe_get());
154                 mSensorManager.sensorManagerDied();
155             }
156         public:
157             explicit DeathObserver(SensorManager& mgr) : mSensorManager(mgr) { } 
158         };
159    
160         mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
161         IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
162  
**//通過SensorServer獲取傳感器列表**
163         mSensors = mSensorServer->getSensorList(mOpPackageName);
164         size_t count = mSensors.size();
165         mSensorList =
166                 static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
167         LOG_ALWAYS_FATAL_IF(mSensorList == NULL, "mSensorList NULL");
168  
**//將傳感器列表存入SensorManager的mSensorList中**
169         for (size_t i=0 ; i<count ; i++) { 
170             mSensorList[i] = mSensors.array() + i;
171         }
172     }
173  
174     return NO_ERROR;
175 }

上面 SensorManager 會等待 SensorService 註冊,
將它保存在成員變量 mSensorServer 中。
小結一下這一段流程的 UML 圖:

https://ithelp.ithome.com.tw/upload/images/20191009/20120515riflLUdlHH.png

SensorManager 功能都來自於 SensorService
它在 Android 的 Sensor 框架中佔據核心位置。
接下來分析一下 SensorService 的相關代碼:

當內核啟動後執行 init 程序,
該程序解析 init.rc 文件 (zygote 包含在 init.${ro.zygote}.rc 中),
rc 文件中指定的應用程序在 app_main.cpp 中,
調用 AndroidRuntime 的 start 方法,
接著通過 JNI 調用 Zyoteinit.java 中的 main 函數,
下一篇從這裡開始追踪。


Reference :

https://blog.csdn.net/dabenxiong666/article/details/80726022


上一篇
[Day-26] Android Pie Sensor (3) 應用
下一篇
[Day-28] Android Pie Sensor (5) 服務 (2)
系列文
Android Pie 底層開發學習心得30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言