Binder連接池

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對象即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章