1 ServiceManger 根據name優先從Map中獲取IBinder,例如AMS、WMS、PMS;若是Map中沒有對應的IBinder,咱們獲取Serviceanager的代理ServiceManagerNative.asInterface(BinderInternal.getContextObject()); android_os_BinderInternal_getContextObject(), 位於android_util_Binder.cpp sp<IBinder> b = ProcessState::self()->getContextObject(NULL) getStrongProxyForHandle(0),獲取handle爲0的BpBinder,即ServiceManager對應的BpBinder javaObjectForIBinder 將IBinder 封裝爲java對象,若是是BBinder封裝爲java 類 Binder,若是是BpBinder,封裝爲BinderProxy,並返回 這裏獲得的返回值爲BinderProxy對象而後將BinderProxy封裝到ServiceMangerProxy中,並返回。 二、ServiceManager的啓動system/core/init/init.c 文件中的main方法中啓動,經過解析init.rc文件中的配置如:service servicemanager system/bin/servicemanager它由Init進程建立,和zygote進程並非同一個進程,固然和Systemserver(AMS、WMS、PMS) 也不是同一個進程三、綁定AMS的binder到ServiceManagerSystemserver 啓動 AMS,startBootstrapServices-->SystemServiceManager.startService(ActivityManagerService.LifeCycle.class)同時,調用ActivityManagerService.setSystemProcess-->ServiceManager.addService(Context.Activity_Service, this, true)而後:ServiceManagerProxy-->addService BinderProxy-->transact() 傳遞AMS Parcel-->writeStrongBinder 封裝AMS, Java層 android_os_parcel-->android_os_parcel_writeStrongBinder() 調用本地方法封裝AMS android_util_Binder-->IBinderForJavaObject, 將AMS映射爲對應的JAVABBinder,保存在JavaBBinderHolder中 Parcel-->writeStrongBinder,封裝BBinder,C++ BpBinder-->transact() 使用ServiceManager對應的BpBinder。 IPCThreadState-->transact() writeTransactData 將數據寫入mOut變量中 waitForResonpse 等待驅動返回數據 talkWidthDriver() ioctl 和驅動交換數據(mOut 寫入驅動, mIn讀出),將BBinder保存在驅動中讀取:ServiceManager.getService(name) ServiceManagerProxy.getService(name) BinderProxy.transact()將服務名稱傳入 BpBinder-->transact(); BpBinder 的地址保存在BinderProxy 中的 long mObject 變量中,而且以此創建聯繫。 IPCThreadState-->transact(); writeTransactData(); waitForResponse() talkWidthDriver() ioctl ..... 將服務經過驅動返回的數據寫入reply 這個parcel結構中,這裏爲對應服務的BpBinder 對應的 handle Parcel readStrongBinder 獲取 IBinder,Java層Parcel 持有 long mNativePtr 爲c層Parcel地址 JavaObjectForIBinder(IBinder *),將BpBinder 轉換爲 BinderProxy Parcel -->readStrongBinder,將BpBinder 從parcel中讀取出來。 將BinderProxy 封裝在ActivityManagerProxy中處理:AMS服務接受驅動信息的流程: IPCThreadState-->talkWithDrive 讀取到從驅動傳來的數據 executeCommand 中處理命令 switch BR_TRANSACT分支,從傳來的數據結構中獲取BBinder 和Parcel等數據 BBinder-->transact(), 這裏實際爲 JavaBBinder,其重寫了onTransact方法 JavaBBinder-->onTransact, 此處的JavaBBinder與AMS綁定 AMS-->transact(), 此處經過JNI中c調Java的方法,調用AMS中的transact AMS-->onTransact()