什麼叫Binder,從不角度理解有不同含義:
從IPC層:binder是安卓跨進程通信的方式。
從安卓driver層:binder是虛擬的物理設備。
從安卓native層:binder是創建 service manager 以及BpBinder和BBinder模型,搭建binder驅動層的橋樑。
從安卓framework層: binder是activitymanager,windmanager等些manager對應的activitymanagerservice,windmanagerservice等service;他們之間的橋樑。
從APP層:binder是客服端和服務端進行通信的媒介,當客服端通過bindservice的時候,服務端返回有個包含服務端業務的binder對象,通過binder對象可以獲取服務端的服務或者數據,即AIDL。
//binder在不同層扮演角色不同,我們先從driver層源碼分析
//driver層版本:kernel_3.18
通過源碼分析核心方法知道binder在驅動層的工作流程
例如通過 binder_init 方法 初始化binder;
binder_open 方法 打開binder設備;
binder_mmap 方法 數據映射;
binder_ioctl 方法 binder數據操作;
在線代碼地址http://androidxref.com/kernel_3.18/xref/drivers/staging/android/binder.c
//native層
說道native層就不得不分析下service manager了,作爲binder的大管家,在整個binder中起到中心樞紐作用
service manger的源碼我可以從四個方面分析
啓動: service manager 通過調用binder_open打開binder設備,
調用binder_become_context_manager 把service manager提升爲binder大管家
調用binder_loop 無限循環, 處理客戶端發來的消息。
源碼:http://androidxref.com/9.0.0_r3/xref/frameworks/native/cmds/servicemanager/service_manager.c
獲取: 通過調用IServiceManager 的defaultServiceManager函數 獲取service manger
源碼: http://androidxref.com/9.0.0_r3/xref/frameworks/native/libs/binder/IServiceManager.cpp
註冊服務 :調用do_add_service 註冊服務
源碼:http://androidxref.com/9.0.0_r3/xref/frameworks/native/cmds/servicemanager/service_manager.c
查詢服務 :調用do_find_service 查詢服務
源碼:http://androidxref.com/9.0.0_r3/xref/frameworks/native/cmds/servicemanager/service_manager.c
BBinder負責把service註冊到service manager;BPBinder負責從service manager獲取需要的service ,調用service的服務。
//framework層
初始化;安卓系統在開機過程,zygote啓動過程會註冊虛擬機,調用jni層的AndroidRunTime ::startReg函數註冊服務
調用jni的Android_util_binder 獲取服務 BinderPorxy
APP層就是AIDL,具體實現代碼可以看 https://blog.csdn.net/qq_36237165/article/details/102458074