线程池机制
核心思路
在 Android 开发中,当多个业务模块需要与同一个服务端进行通信时,如果每个模块都独立创建 Service 实例,不仅浪费资源,还会增加进程管理的复杂度。Binder 线程池的核心作用在于统一管理这些请求,将不同业务模块的 Binder 调用统一转发到远程 Service 执行,从而避免重复创建 Service。
大致流程如下:
- 各业务模块定义自己的 AIDL 接口并实现具体逻辑,确保模块间无耦合。
- 向服务端注册唯一标识及对应的 Binder 对象。
- 服务端提供一个统一的
queryBinder接口,根据标识返回相应的 Binder 对象。 - 客户端获取 Binder 后直接进行远程方法调用。

下面我们通过代码模拟这一过程。
接口定义
首先创建两个 AIDL 接口来模拟不同的业务需求,例如安全中心和计算服务。
ISecurityCenter.aidl
// ISecurityCenter.aidl
package com.breezehan.ipc.binderpool;
interface ISecurityCenter {
String encrypt(String content);
String decrypt(String password);
}
ICompute.aidl
// ICompute.aidl
package com.breezehan.ipc.binderpool;
interface ICompute {
int add(int a, int b);
}
服务端实现
接下来实现上述接口。这里注意,AIDL 生成的 Stub 类通常用于转换接口和 Binder 对象。
public class SecurityCenterImpl extends ISecurityCenter.Stub {
private static final char SECRET_CODE = '^';
@Override
public String encrypt(String content) throws RemoteException {
char[] chars = content.toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] ^= SECRET_CODE;
}
(chars);
}
String RemoteException {
encrypt(password);
}
}
.Stub {
RemoteException {
a + b;
}
}

