IPC机制——Binder连接池

本文介绍了Android中Binder连接池的概念,阐述了通过AIDL实现进程间通信的流程,并详细讲解了Binder连接池的优点,旨在减少Service数量,提高系统资源利用率。提供客户端和服务端的代码示例,帮助理解如何在实际项目中应用Binder连接池。
摘要由CSDN通过智能技术生成

IPC机制——Binder连接池

AIDL

AIDL是一种最常用的进程间通信方式,是开发中设计进程间通信时的首选。

大致流程:

1.创建一个Service和一个AIDL接口

2.创建一个类继承自AIDL接口中的Stub类并实现Stub类中的抽象方法,在Service的onBind方法中返回这个类的对象。

3.客户端绑定服务端Service,建立连接后就可以访问远程服务端了。

Binder连接池优点

当需求越来越多,项目越来越庞大,功能越来越复杂,假如现在有10个不同的业务模块都需要使用AIDL来进行进程间通信,可以按照AIDL的实现方式创建10个Service.那如果是有100个地方需要用到AIDL的时候我们不能无限制的增加Service,Service是Android四大组件之一,属于系统资源,应用设计应该轻量级。设计初期应该尽量减少Service的数量,将所有的AIDL放到一个Service中去管理。工作原理如下:

在这里插入图片描述

代码示例

客户端

下边对Binder连接池的使用步骤进行代码实现

第一步:创建一个工程作为Client端,在main目录下创建aidl文件夹,在该文件夹下创建一个目录存放我的aidl文件:
在这里插入图片描述

IBinderPool.aidl

// IBinderPool.aidl
package com.support.mediacommunication;
// Declare any non-default types here with import statements
interface IBinderPool {
   
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    IBinder queryBinder(int binderCode);
}

IAudioRecordService.aidl

interface IAudioRecordService {
   
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
 oneway  void startRecording(int recordSource,String pkgName);
 oneway  void stopRecording(String pkgName);
}

ICameraService.aidl

interface ICameraService {
   
    void openCamera(int cameraId,int openMode,String packageName);
    void releaseCamera(String packageName);
    int yuvDataLength();
}

aidl文件写好后,编译一下,或者也可以clean一下工程,就会在app\build\generated\aidl_source_output_dir\debug\compileDebugAidl\out\com\support\mediacommunication目录下生成对应aidl的java接口文件。

第二步:开始写客户端连接服务器代码,以IAudioRecordService为例

private IAudioRecordService mAudioProxy;
 //Bridges used to connect services
    private ServiceConnection mConnection = new ServiceConnection() {
   
        @Override
        public void onServiceDisconnected(ComponentName name) {
   
            if (DEBUG) Log.d(TAG, "service disconnected")<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值