Binder连接池

本文介绍如何通过Binder连接池统一管理多个AIDL接口,包括IEncryption和ICompute接口的实现,以及如何在BinderPoolService中进行注册和服务提供。通过BinderPool类与服务建立连接,实现远程调用。
摘要由CSDN通过智能技术生成

Binder连接池管理多个AIDL接口处理。
创建IEncryption.aidl和ICompute.aidl

// IEncryption.aidl
package com.example.test.binders;
// Declare any non-default types here with import statements
interface IEncryption {
    void encrypt(String content);
    void decrypt(String password);
}

// ICompute.aidl
package com.example.test.binders;
// Declare any non-default types here with import statements
interface ICompute {
    int add(int a ,int b);
}

2个AIDL接口的实现
IEncryptionImpl和IComputeImpl

package com.example.test.binders;

import android.os.RemoteException;

/**
 * Description:
 */

public class IEncryptionImpl extends IEncryption.Stub{
    private static final char SECRETCODE = '^';
    @Override
    public String encrypt(String content) throws RemoteException {
        char[] chars = content.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            chars[i] ^= SECRETCODE;
        }
        return new String(chars);

    }

    @Override
    public String decrypt(String password) throws RemoteException {
        return encrypt(password);
    }
}

package com.example.test.binders;

import android.os.RemoteException;

/**
 * Description:
 */

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

接下来为BInder连接池创建AIDL接口 IBinderPool.aidl

// IBinderPool.aidl
package com.example.test.binders;
// Declare any non-default types here with import statements
interface IBinderPool {
    IBinder queryBinder(int binderCode);
}

IBinderPool.aidl的实现IBinderPoolImpl

package com.example.test.binders;

import android.os.IBinder;
import android.os.RemoteException;

import com.example.test.utils.Constants;

/**
 * Description:
 */

public class IBinderPoolImpl extends IBinderPool.Stub{
    @Override
    public IBinder queryBinder(int binderCode) throws RemoteException {
        IBinder mIBinder = null;
        switch (binderCode){
            case Constants.ICOMPUTECODE:
                mIBinder = new IComputeImpl();
                break;
            case Constants.IENCRYPTIONCODE:
                mIBinder = new IEncryptionImpl();
                break;
            default:
                break;
        }
        return mIBinder;
    }
}

使用Service管理Binder连接池,创建BinderPoolService

package com.example.test.binders;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Description:
 */

public class BinderPoolService extends Service {
    private static final String TAG = "BinderPoolService";

    private Binder mBinderPool = new IBinderPoolImpl();
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinderPool;
    }

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

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

在AndroidManifest.xml注册

		<service android:name=".binders.BinderPoolService"
                 android:process=":BinderPoolService">

        </service>

创建BinderPool来和BinderPoolService建立连接

package com.example.test.binders;

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 com.example.test.provider.DBSqlitOpenHelper;

import java.util.concurrent.CountDownLatch;

/**
 * Description:
 */

public class BinderPool {
    private Context mContext;
    private BinderPool(Context context) {
        mContext = context;
        connectBinderPoolService();
    }
    private IBinderPool mIBinderPool;

    private static BinderPool instance = null;
    public static BinderPool getInstance(Context context) {
        if (instance == null) {
            synchronized (BinderPool.class) {
                if (instance == null)
                    instance = new BinderPool(context);
            }
        }
        return instance;
    }
    private CountDownLatch mCountDownLatch;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIBinderPool = IBinderPool.Stub.asInterface(service);
            try {
                mIBinderPool.asBinder().linkToDeath(mDeathRecipient,0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            // 计数减一
            mCountDownLatch.countDown();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            mIBinderPool.asBinder().unlinkToDeath(mDeathRecipient,0);
            mIBinderPool = null;
            connectBinderPoolService();
        }
    };

    private void connectBinderPoolService() {
        //实例化一个倒计数器,count指定计数个数
        mCountDownLatch = new CountDownLatch(1);
        Intent intent = new Intent(mContext,BinderPoolService.class);
        mContext.bindService(intent,mServiceConnection,Context.BIND_AUTO_CREATE);

        try {
            //等待,当计数减到0时,所有线程并行执行
            mCountDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

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

创建BinderPoolActivity

package com.example.test.binders;

import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.test.R;
import com.example.test.utils.Constants;

public class BinderPoolActivity extends AppCompatActivity {

    private static final String TAG = "BinderPoolActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binder_pool);
        initData();
    }

    private void initData() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                go();
            }
        }).start();


    }

    private void go() {
        BinderPool binderPool = BinderPool.getInstance(BinderPoolActivity.this);
        IBinder encryptionIBinder = binderPool.queryBinder(Constants.IENCRYPTIONCODE);
        IEncryption iEncryption = IEncryption.Stub.asInterface(encryptionIBinder);
        String mContent = "abcdefghijklmnopqrstuvwxyz";
        Log.e(TAG, "initData: 原始数据: "+mContent);
        try {
            String password = iEncryption.encrypt(mContent);
            Log.e(TAG, "initData: 转换后数据: "+password);

            String decryptContent = iEncryption.decrypt(password);
            Log.e(TAG, "initData: 解密后原始数据: "+decryptContent);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        IBinder computeIBinder = binderPool.queryBinder(Constants.ICOMPUTECODE);
        ICompute iCompute = ICompute.Stub.asInterface(computeIBinder);
        try {
            Log.e(TAG, "initData: 100 + 200 = "+iCompute.add(100,200));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

运行结果
在这里插入图片描述当有新的AIDL接口时,在实现了自己的AIDL接口后,只需要修改BinderPoolImpl中的queryBinder方法,并添加一个新的binderCode并返回对应的Binder对象即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值