Binder作为AIDL通信的核心, 在使用中经常需要重复利用, 动态管理AIDL接口. Binder连接池的主要作用是把Binder请求统一发送至Service执行, 即动态管理Binder操作, 避免重复创建Service. 本文使用两种简单的AIDL服务, 使用Binder连接池动态切换, 含有演示Demo.
更多: http://www.wangchenlong.org/
欢迎Follow我的GitHub: https://github.com/SpikeKing
本文源码的GitHub下载地址
AIDL
模拟Binder连接池, 使用两个简单的AIDL接口与实现, 一个是加解密, 一个是加法.
加解密, AIDL提供两个方法, 即加密字符串和解密字符串.
1 | package org.wangchenlong.binderpooldemo; |
加密和解密的实现, 使用简单的异或运算处理.
1 | public class SecurityCenterImpl extends ISecurityCenter.Stub { |
AIDL的实现方法都需要设置
RemoteException
的异常抛出, 防止连接异常.
求和的AIDL接口
1 | package org.wangchenlong.binderpooldemo; |
求和的实现, 非常简单.
1 | public class ComputeImpl extends ICompute.Stub { |
Binder连接池通过ID查找Bidner, 查询并返回匹配的Binder.
1 | package org.wangchenlong.binderpooldemo; |
Binder 连接池
Service服务通过Binder
连接池动态选择Binder
请求.
1 | private Binder mBinderPool = new BinderPool.BinderPoolImpl(); // 动态选择Binder |
Binder连接池的具体实现, 创建BinderPool
单例, 连接服务.
1 | private BinderPool(Context context) { |
绑定服务, 通过CountDownLatch
类, 把异步操作转换为同步操作, 防止绑定冲突.
1 | private synchronized void connectBinderPoolService() { |
通过DeathRecipient
处理Binder连接池死亡重联机制.
1 | // 失效重联机制, 当Binder死亡时, 重新连接 |
通过ID连接不同的Binder
请求.
1 | public IBinder queryBinder(int binderCode) { |
Binder连接池AIDL的具体实现, 通过ID选择Binder.
1 | public static class BinderPoolImpl extends IBinderPool.Stub { |
AIDL并不会直接生成, 使用AS的
Build -> Make Project
即可.
客户端
通过AIDL接口, 把耗时任务移到Service进行. 操作Binder需要在其他线程中执行, 使用Handler回调至主线程, 并更新页面.
1 | public void encryptMsg(View view) { |
其他线程使用
Handler
向主线程传递数据, 在界面中显示效果.
加法操作类似.
1 | public void addNumbers(View view) { |
注意AIDL需要捕获
RemoteException
的异常.
效果
AIDL是较为高效的跨进程通信方式, 也是很多方式的低层实现; Binder连接池可以在同一服务中处理多个Binder请求, 节省资源, 因此需要熟练掌握.
OK, that’s all! Enjoy it!
最初发布地址:
http://www.wangchenlong.org/2016/08/07/1608/074-aild-binder-pool/
欢迎Follow我的GitHub, 关注我的简书, CSDN, 掘金.
我已委托“维权骑士”为我的文章进行维权行动. 未经授权, 禁止转载, 授权或合作请留言.