Android中AIDL的使用(二) 之 Binder连接池

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lyz_zyx/article/details/83062386

我们在上一篇文章《Android中AIDL的使用》中已经学习了AIDL的使用方法,同时也已经能满足基本开发需求了。但是当随着项目越来越大,不同的业务模块都需要使用AIDL来进行IPC的话,那么我们就得不断地增加Service来满足需求了。我们知道Service是四大组件之一、一种系统资源,太多的Service会使得我们的应用看起来很重量级,这样明显不是明智的解决方案。在《Android开发艺术探索》书中作者给出了一个很好的解决方案,那就是Binder连接池。今天我们就来看看这个Binder连接池是怎么实现的。

Binder连接池的工作原理

Binder连接池的原理其实也是很好理解的,就是只有一个Service,对于不同的客户端返回一个不同的Binder。这个Binder连接池类似于一个工厂方法模式。为每一个客户端创建他们所需要的Binder对象。它的工作原理就如下图所示:

Binder连接池的实现

第一步,假设目前需求是需要两个AIDL接口,来实现加密解密和计算的功能,那么先新建ISecurityCenter.aidl 和 ICompute.aidl文件以及它们的实现类:

package com.zyx.binderpooldemo;

interface ISecurityCenter {
    String encrypt(String content);
    String decrypt(String password);
}
package com.zyx.binderpooldemo;

interface ICompute {
    int add(int a, int b);
}
package com.zyx.binderpooldemo;

import android.os.RemoteException;

public class SecurityCenterImpl extends ISecurityCenter.Stub {
    private static final char SECRET_CODE = '^';
    @Override
    public String encrypt(String content) throws RemoteException {
        // TODO 功能实现略
        return "加密后的字符串";
    }
    @Override
    public String decrypt(String password) throws RemoteException {
        // TODO 功能实现略
        return "解密后的字符串";
    }
}
package com.zyx.binderpooldemo;

import android.os.RemoteException;

public class ComputeImpl extends ICompute.Stub {
    @Override
    public int add(int a, int b) throws RemoteException {
        return a + b;
    }
}

第二步,为Binder连接池创建IBinderPool.aidl文件

package com.zyx.binderpooldemo;

interface IBinderPool {
    IBinder queryBinder(int binderCode);
}

第三步,创建远程服务BinderPoolService.java:

package com.zyx.binderpooldemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;

public class BinderPoolService extends Service {
    public static final int BINDER_COMPUTE = 0;
    public static final int BINDER_SECURITY_CENTER = 1;

    private Binder mBinderPool = new BinderPoolImpl();

    public static class BinderPoolImpl extends IBinderPool.Stub {
        @Override
        public IBinder queryBinder(int binderCode) throws RemoteException {
            IBinder binder = null;
            switch (binderCode) {
                case BINDER_SECURITY_CENTER: {
                    binder = new SecurityCenterImpl();
                    break;
                }
                case BINDER_COMPUTE: {
                    binder = new ComputeImpl();
                    break;
                }
                default:
                    break;
            }
            return binder;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return mBinderPool;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

说明

  1. 内部类BinderPoolImpl继承于IBinderPool.Stub,根据客户端传入的code来决定实例化相应用Binder对象并返回。

 

第四步,是重点步聚,新建一个BinderPool类用于专门处理Binder连接池的绑定Service和获取对应Binder对象:

package com.zyx.binderpooldemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import java.util.concurrent.CountDownLatch;

public class BinderPool {

    // 单例
    private static volatile BinderPool sInstance;
    public static BinderPool getInsance(Context context) {
        if (sInstance == null) {
            synchronized (BinderPool.class) {
                if (sInstance == null) {
                    sInstance = new BinderPool(context);
                }
            }
        }
        return sInstance;
    }

    private Context mContext;
    private IBinderPool mBinderPool;
    // 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待(异步转同步)
    private CountDownLatch mConnectBinderPoolCountDownLatch;

    private BinderPool(Context context) {
        mContext = context.getApplicationContext();
        connectBinderPoolService();
    }

    // 绑定服务
    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();
        }
    }

    private ServiceConnection mBinderPoolConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 连接上服务后,获取服务里远程提供的Binder mBinderPool对象,它是前面的IBinderPool接口
            mBinderPool = IBinderPool.Stub.asInterface(service);
            try {
                // linkToDeath可以给Binder设置一个死亡代理
                mBinderPool.asBinder().linkToDeath(mBinderPoolDeathRecipient, 0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            mConnectBinderPoolCountDownLatch.countDown();
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private IBinder.DeathRecipient mBinderPoolDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            mBinderPool.asBinder().unlinkToDeath(mBinderPoolDeathRecipient, 0);
            mBinderPool = null;
            // 重新绑定服务
            connectBinderPoolService();
        }
    };

    public IBinder queryBinder(int binderCode) {
        IBinder binder = null;
        try {
            if (mBinderPool != null) {
                binder = mBinderPool.queryBinder(binderCode);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return binder;
    }
}

说明:

  1. BinderPool的实现方式是一个单例,并在构造函数中实现了Service的绑定
  2. Service的绑定过程中使用了CountDownLatch来进行同步执行,以确保客户端在执行调用之前已经绑定好服务端
  3. 绑定Service完成后,获得一个mBinderPool对象,并为其设置一个死亡代理,使在意外断开后能重新绑定
  4. 对外提供queryBinder方法,通过约定的code调用mBinderPool 对象的queryBinder方法返回相应用Binder对象

 

最后一步,就是客户端的调用了:

private void doWork() {
    BinderPool binderPool = BinderPool.getInsance(MainActivity.this);

    IBinder securityBinder = binderPool.queryBinder(BinderPoolService.BINDER_SECURITY_CENTER);
    mSecurityCenter = SecurityCenterImpl.asInterface(securityBinder);
    try {
        String msg = "hello world";
        String password = mSecurityCenter.encrypt(msg);
        String originalPassword  = mSecurityCenter.decrypt(password);
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    IBinder computeBinder = binderPool.queryBinder(BinderPoolService.BINDER_COMPUTE);
    mCompute = ComputeImpl.asInterface(computeBinder);
    try {
        int reuslt = mCompute.add(3, 5);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

说明

  1. 因为BinderPool的初次调用会初始化单例对象,而该对象是一个耗时的同步操作,建议在线程中执行
  2. 获得binderPool对象后便可通过code获得相应的加密解密Binder对象securityBinder 计算Binder对象computeBinder进行各自的方法调用。

 

点击下载示例源码

 

——本文部分内容参考自《Android开发艺术探索》

 

猜你喜欢

转载自blog.csdn.net/lyz_zyx/article/details/83062386