Android OS的核心设计思想是component,而支持component的基石则是Inter-component-communication/Inter-process-communication,而不同抽象层次的ICC/IPC都是由Binder来实现的。
从概念上来说,Binder采用C/S通信Model。传送的数据存放于Transaction中,为了能把不同结构的数据放入Transaction,传输前后必须进行序列化和反序列化。通过Death Notification能够知道Binder是否还活着。为了让C能找到S,有两种方式:注册service和匿名service,注册service架构类似于Mediator design pattern, 匿名service则是通过Intent。Binder的Security 通过携带双方的PID,UID完成。
从实现上来说,Binder采用分层模型。从上到下分别为:Java app层主要是通过AIDL在client侧生成访问service的proxy,在service侧生成带有remote method实现的stub;Java API层除了封装底层Binder middleware以外,引入了Intent的相关facilities;C++ middleware主要负责管理request working的进程/线程,marshalling/unmarshalling data,与binder driver 交互;Binder driver负责安全可靠的在process之间转发message。
1. Components IPC以及Binder的作用
1.1 Android涉及的4种Component
Android 4种Component 的hierarchical class diagram如下:
Activity代表App的一个UI,主要负责显示和接受user输入。由于可能被另一个位于前端的Activity置于睡眠状态,一般不存放persistent data。
Service主要服务于需要长期存在的目的。由于service只有在system 的memory耗尽需要kill app来释放内存时才会被强制停止,所有后台处理的工作都应该放置于此。
ContentProvider一般用于管理persistent data。它提供访问persistent data 的interface,这个接口类似于file/network stream 以及SQL DB。
BroadcastReceiver用于接受系统发送的message。
1.2 Components之间的通信
虽然通信的形式有Intent、ContentProvider、Messager,但基石都是Binder。
1.2.1 Component通信举例
既然Component各有分工,他们之间就需要通信来相互合作。如下图所示,Activity通过Intent来start,同时通过Intent将另一个Activity带到前台;Service能够通过Intent被start/stop/bind,同时也是通过Intent来return; ContentProvider 能够通过CRUD被访问;BroadcastReceiver能够接受订阅的Intent。