IPC机制——Binder连接池
AIDL
AIDL是一种最常用的进程间通信方式,是开发中设计进程间通信时的首选。
大致流程:
1.创建一个Service和一个AIDL接口
2.创建一个类继承自AIDL接口中的Stub类并实现Stub类中的抽象方法,在Service的onBind方法中返回这个类的对象。
3.客户端绑定服务端Service,建立连接后就可以访问远程服务端了。
Binder连接池优点
当需求越来越多,项目越来越庞大,功能越来越复杂,假如现在有10个不同的业务模块都需要使用AIDL来进行进程间通信,可以按照AIDL的实现方式创建10个Service.那如果是有100个地方需要用到AIDL的时候我们不能无限制的增加Service,Service是Android四大组件之一,属于系统资源,应用设计应该轻量级。设计初期应该尽量减少Service的数量,将所有的AIDL放到一个Service中去管理。工作原理如下:
代码示例
客户端
下边对Binder连接池的使用步骤进行代码实现
第一步:创建一个工程作为Client端,在main目录下创建aidl文件夹,在该文件夹下创建一个目录存放我的aidl文件:
IBinderPool.aidl
// IBinderPool.aidl
package com.support.mediacommunication;
// Declare any non-default types here with import statements
interface IBinderPool {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
IBinder queryBinder(int binderCode);
}
IAudioRecordService.aidl
interface IAudioRecordService {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
oneway void startRecording(int recordSource,String pkgName);
oneway void stopRecording(String pkgName);
}
ICameraService.aidl
interface ICameraService {
void openCamera(int cameraId,int openMode,String packageName);
void releaseCamera(String packageName);
int yuvDataLength();
}
aidl文件写好后,编译一下,或者也可以clean一下工程,就会在app\build\generated\aidl_source_output_dir\debug\compileDebugAidl\out\com\support\mediacommunication目录下生成对应aidl的java接口文件。
第二步:开始写客户端连接服务器代码,以IAudioRecordService为例
private IAudioRecordService mAudioProxy;
//Bridges used to connect services
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
if (DEBUG) Log.d(TAG, "service disconnected")<