之前几篇文章分别写了几种不同的IPC方式,不同的方式有不同的特点和使用场景。
在进程间通信是,AIDL是首选。很多时候开发过程中不仅仅至于要一个ADIL接口,当接口过多的时候需要创建多个Service,这样就比较不方便而且占用系统资源。所以又出现了Binder连接池。这里简单记录一下使用方法。
工作机制是:每个业务模块创建自己的AIDL接口,并实现此接口,这时候不同业务模块之间是不能有耦合的,所以实现细节都要单独开来,然后向服务端提供自己的唯一标识和其对于的Binder对象。对于服务端来说,只需要一个Service即可,服务端提供一个queryBinder接口,这个接口能够根据业务模块的特征来返回相应的Binder对象给它们,不同的业务模块拿到所需的Binder对象后就可以进行远程方法调用了。由此可见,Binder连接池的主要作用就是将每个业务模块的Binder请求统一转发的远程Service中去执行,从而避免了重复创建的过程。
个人理解:Binder连接池就是一个中转站,通过Binder连接池来实现AIDL接口和Service的交互。
举个例子:
创建两个ADIL接口:分布是ISecurityCenter.aild, ICompute.aidl
// ISecurityCenter.aidl
package com.kevin.testaidl;
// Declare any non-default types here with import statements
interface ISecurityCenter {
String encrypt(String content);
String decrypt(String password);
}
————————————————————————————————
// ICompute.aidl
package com.kevin.testaidl;
// Declare any non-default types here with import statements
interface ICompute {
int add(int a,int b);
}
分布为上面两个接口创建实现类:
/**
* Created by Kevin on 2019/4/11<br/>
* Blog:https://blog.csdn.net/student9128<br/>
* Describe:<br/>
*/
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;
}
return new String(chars);
}
@Override
public String decrypt(String password) throws RemoteException {
return encrypt(password);
}
}
—————————————————————
/**
* Created by Kevin on 2019/4/11<br/>
* Blog:https://blog.csdn.net/student9128<br/>
* Describe:<br/>
*/
public class ComputeImpl extends ICompute.Stub {
@Override
public int add(int a, int b) throws RemoteException {
return a+b;
}
}
再创建一个IBinderPool.aidl
// IBinderPool.aidl
package com.kevin.testaidl;
// Declare any non-default types here with import statements
interface IBinderPool {
/**
* @param binderCode,the unique token of specific Binder<br/>
* @return specific Binder who's token is binderCode.
*/
IBinder queryBinder(int binderCode);
}
创建一个BinderPool类:
该类中实现了一个单例方法,保证BinderPool初始化一次,初始中进行了connectBinderPoolService对Binder池进行绑定。同时内部创建了一个静态内部类BinderPoolImpl类实现了queryBinde接口,该方法中主要通过binderConder获取相关的AIDL接口实现类,如代码所示。
/**
* Created by Kevin on 2019/4/11<br/>
* Blog:https://blog.csdn.net/student9128<br/>
* Describe:<br/>
*/
public class BinderPool {
private static final String TAG = "BinderPool";
public static final int BINDER_NONE = -1;
public static final int BINDER_COMPUTE = 0;
public static final int BINDER_SECURITY_CENTER = 1;
private Context mContext;
private IBinderPool mBinderPool;
private static volatile BinderPool sInstance;
private CountDownLatch mConnectBinderPoolCountDownLatch;
private BinderPool(Context context) {
mContext = context.getApplicationContext();
connectBinderPoolService();
}
public static BinderPool getInstance(Context context) {
if (sInstance == null) {
synchronized (BinderPool.class) {
sInstance = new BinderPool(context);
}
}
return sInstance;
}
/**
* 绑定Binder池服务
*/
private synchronized void connectBinderPoolService() {
mConnectBinderPoolCountDownLatch = new CountDownLatch(1);
Intent service = new Intent(mContext, BinderPoolService.class);
mContext.bindService(service, mBinderPoolConnection, Context.BIND_AUTO_CREATE);
try {
mConnectBinderPoolCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 根据binderCode来查询Binder
* @param binderCode
* @return Binder
*/
public IBinder queryBinder(int binderCode) {
if (mBinderPool != null) {
try {
return mBinderPool.queryBinder(binderCode);
} catch (RemoteException e) {
e.printStackTrace();
}
}else {
//为null
}
return null;
}
private ServiceConnection mBinderPoolConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBinderPool = IBinderPool.Stub.asInterface(service);
try {
mBinderPool.asBinder().linkToDeath(mBinderPoolDeathRecipient, 0);
} catch (RemoteException e) {
e.printStackTrace();
}
mConnectBinderPoolCountDownLatch.countDown();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
/**
* Binder意外死亡,重新连接服务
*/
private IBinder.DeathRecipient mBinderPoolDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
mBinderPool.asBinder().unlinkToDeath(mBinderPoolDeathRecipient, 0);
mBinderPool = null;
connectBinderPoolService();//重新连接服务
}
};
public static class BinderPoolImpl extends IBinderPool.Stub {
public BinderPoolImpl() {
super();
}
@Override
public IBinder queryBinder(int binderCode) throws RemoteException {
switch (binderCode) {
case BINDER_NONE:
return null;
case BINDER_COMPUTE:
return new ComputeImpl();
case BINDER_SECURITY_CENTER:
return new SecurityCenterImpl();
default:
return null;
}
}
}
}
服务端:
Service会根据queryBinder在onBind中返回相对应的相关的IBinder对象
public class BinderPoolService extends Service {
private static final String TAG = "BinderPoolService";
private Binder mBinderPool = new BinderPool.BinderPoolImpl();
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return mBinderPool;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
客户端:
通过 BinderPool binderPool = BinderPool.getInstance(this);
来连接服务,绑定Binder连接池。
通过 binderCode来获取相关的Binder,去调用相对于的服务,如下代码所示
/**
* Created by Kevin on 2019/4/11<br/>
* Blog:https://blog.csdn.net/student9128<br/>
* Describe:<br/>
*/
public class BinderPoolActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
private ISecurityCenter mSecurityCenter;
private ICompute mCompute;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
super.run();
doWork();
}
}.start();
}
});
}
private void doWork() {
BinderPool binderPool = BinderPool.getInstance(this);
IBinder securityBinder = binderPool.queryBinder(BinderPool.BINDER_SECURITY_CENTER);//注意此处,不同的binderCode
mSecurityCenter = SecurityCenterImpl.asInterface(securityBinder);
try {
String encryptStr = mSecurityCenter.encrypt("Hello Android");
Log.d(TAG, "encryptStr=" + encryptStr);
String decryptStr = mSecurityCenter.decrypt(encryptStr);
Log.d(TAG, "decryptStr=" + decryptStr);
} catch (RemoteException e) {
e.printStackTrace();
}
Log.d(TAG, "execute compute method");
IBinder computeBinder = binderPool.queryBinder(BinderPool.BINDER_COMPUTE);//注意此处,不同的binderCode
mCompute = ComputeImpl.asInterface(computeBinder);
try {
int addResult = mCompute.add(2, 3);
Log.d(TAG, "2+3=" + addResult);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
Binder连接池的实现中,通过CountDownLatch将binderService这一异步操作转换成了同步操作,这就意味着可能是耗时的,所以调用的过程中开了一个线程
注:本文章知识点来自学习《Android开发艺术探索》一书