欢迎Follow我的GitHub
Binder作为AIDL通信的核心, 在使用中经常需要重复利用, 动态管理AIDL接口. Binder连接池的主要作用是把Binder请求统一发送至Service执行, 即动态管理Binder操作, 避免重复创建Service. 本文使用两种简单的AIDL服务, 使用Binder连接池动态切换, 含有演示Demo.
本文源码的GitHub下载地址
AIDL
模拟Binder连接池, 使用两个简单的AIDL接口与实现, 一个是加解密, 一个是加法.
加解密, AIDL提供两个方法, 即加密字符串和解密字符串.
package org.wangchenlong.binderpooldemo;
interface ISecurityCenter {
String encrypt(String content);
String decrypt(String password);
}
加密和解密的实现, 使用简单的异或运算处理.
public class SecurityCenterImpl extends ISecurityCenter.Stub {
private static final char SECRET_CODE = 'w';
@Override public String encrypt(String content) throws RemoteException {
char[] chars = content.toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] ^= SECRET_CODE;
}
return new String(chars);
}
@Override public String decrypt(String password) throws RemoteException {
return encrypt(password);
}
}
AIDL的实现方法都需要设置
RemoteException
的异常抛出, 防止连接异常.
求和的AIDL接口
package org.wangchenlong.binderpooldemo;
interface ICompute {
int add(int a, int b);
}
求和的实现, 非常简单.
public class ComputeImpl extends ICompute.Stub {
@Override public int add(int a, int b) throws RemoteException {
return a + b;
}
}
Binder连接池通过ID查找Bidner, 查询并返回匹配的Binder.