之前幾篇文章分別寫了幾種不同的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開發藝術探索》一書