AIDL用法四 Binder连接池

前言

现在考虑一个情况,公司的项目越做越大了,有很多不同功能的业务模块需要使用AIDL来进行通信,如果还是按照原来的方式,则需要创建很多service,这明显不符合多态的特性。像写接口一样,找出这些AIDL的共同点做出一个接口,那么AIDL的共同点就是他们底层都是用binder来通信的。

我们将这些binder管理起来,通过接口来选择性调用。当然这个接口肯定是AIDL文件。

好,现在先建两个业务模块

// ISecurityCenter.aidl
package xxxxxxxxxxx;

interface ISecurityCenter {
    String encrypt(String content);
        String decrypt(String password);
}
// ICompute.aidl
package com.example.myapplication;

// Declare any non-default types here with import statements

interface ICompute {
    int add(int a, int b);
}

和一个管理binder的AIDL接口

interface IBinderPool {
   IBinder queryBinder(int binderCode);
}

接着,实现以上三个aidl的具体业务逻辑

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

    private static final char SECRET_CODE = '^';

    @Override
    public String encrypt(String content) throws RemoteException {
        return content+"haha";
    }

    @Override
    public String decrypt(String password) throws RemoteException {
        return password.toLowerCase();
    }
}
public class BinderPoolImpl extends IBinderPool.Stub {
    @Override
    public IBinder queryBinder(int binderCode) throws RemoteException {
        IBinder binder=null;
        switch (binderCode){
            case 1:
                binder=new SecurityCenterImpl();
                break;
            case 2:
                binder=new ComputeImpl();
                break;
            default:
                break;
        }

        return binder;
    }
}

创建一个binder连接池类。在它的内部,首先要去绑定远程服务,绑定成功后,客户端就可以通过useAidlByCode方法去获取各自对应的binder,拿到所需得到binder以后,不同业务模块就可以进行各自的操作。

public class BinderPoolUtil {

    private Context mcontext;
    private static  volatile BinderPoolUtil sInstance;
    private CountDownLatch mCountDownLatch;

    private IBinderPool binderPoolimpl=new BinderPoolImpl();

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binderPoolimpl = IBinderPool.Stub.asInterface(iBinder);
            try {
                binderPoolimpl.asBinder().linkToDeath(mDeathRecipient,0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            mCountDownLatch.countDown();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };


    private  BinderPoolUtil(Context mcontext) {
        this.mcontext = mcontext;
        useThisBindService();
    }




    public static BinderPoolUtil getInstance (Context context){
        if(sInstance==null){
            synchronized (BinderPoolUtil.class){
                if(sInstance==null){
                    sInstance=new BinderPoolUtil(context);
                }
            }
        }
        return sInstance;
    }

    //使用这个类帮A绑定服务了
    private synchronized  void  useThisBindService(){
        mCountDownLatch = new CountDownLatch(1);
        Intent intent = new Intent(mcontext, MyService.class);

        mcontext.bindService(intent, mServiceConnection,Context.BIND_AUTO_CREATE);

        try {
            mCountDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     *      通过code来调用不同的Aidl模块功能
     * @param binderCode
     * @return
     */

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

        return binder;

    }


    private IBinder.DeathRecipient mDeathRecipient=new IBinder.DeathRecipient(){

        @Override
        public void binderDied() {
            binderPoolimpl.asBinder().unlinkToDeath(this,0);
            binderPoolimpl=null;
            useThisBindService();
        }
    };




}

服务的代码则简单

public class MyService extends Service {



    @Override
    public void onCreate() {
        super.onCreate();
    }


    private BinderPoolImpl stub=new BinderPoolImpl();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return stub;
    }

}

然后在界面中调用binder连接池方法类查询

public class MainActivity extends AppCompatActivity {



        private BinderPoolUtil binderPoolUtil;
        private IBinder scbinder;
        private IBinder cibinder;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    binderPoolUtil = BinderPoolUtil.getInstance(MainActivity.this);
                    scbinder = binderPoolUtil.useAidlByCode(1);
                    cibinder = binderPoolUtil.useAidlByCode(2);
                    ISecurityCenter iSecurityCenter = SecurityCenterImpl.asInterface(scbinder);
                    ICompute iCompute = ComputeImpl.asInterface(cibinder);
                    String s1 = iSecurityCenter.encrypt("sfeMHJI");
                    String s2 = iSecurityCenter.decrypt("sfeMHJI");
                    int add = iCompute.add(1, 2);

                    Log.e("yjm",s1+"--------"+s2+"--------"+add);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

你可能感兴趣的:(AIDL用法四 Binder连接池)