BluetoothKit源码解读
2017-10-07 本文已影响34人
LeonXtp
BluetoothKit
项目主要类图结构
代理模式
IBluetoothClient
接口
BluetoothClient
代理实现类
BluetoothClientImpl
真正的实现类
线程切换
进程管理
- Service
- Binder
- AIDL
为什么没有开启新进程,却要使用AIDL?
单例管理
蓝牙交互逻辑
所有的方法调用,都统一通过safeCallBluetoothApi()
方法跨进程调用,使用code区分方法,使用Bundle
传递参数以及回调。
在执行完毕后,通过跨进程调起回调。
流程/角色解析
一次搜索设备的任务分配和执行流程
-
BluetoothSearchManager
:负责管理搜索开启、回调和停止- 将
SearchRequest
包装成BluetoothSearchRequest
(作用:将已连接的设备放入搜索结果中)
- 将
-
将每一个搜索任务都封装到
BluetoothSearchTask
中 -
BluetoothSearcher
抽象的扫描任务执行者-
BluetoothLESearcher
:负责BLE设备扫描,继承自BluetoothSearcher
,真正的扫描执行者 -
BluetoothClassicSearcher
:负责经典蓝牙设备扫描,继承自 -
BluetoothAdapter
:Android原生的蓝牙适配器,终于,本库调用它的startLeScan()
方法正式开启扫描!!!
-
-
然后再层层往上回调,最后到达
Service
中,再通过binder回调到调用进程的工作线程。
一次写入设备的任务分配和执行流程
-
BleConnectManager
:代理的连接管理器,负责管理连接、写入、读取、注册通知、读取RSSI等。 -
BleConnectMaster
:被代理的连接管理者,真正负责上述任务。 -
BleConnectDispatcher
:任务分发器,将上述各种任务封装成各种BleRequest
,然后分发到各自的执行者 -
BleWriteRequest
:BleRequest
的一个具体写入实现,在其startWrite()
方法中,开始写入 -
BleConnectWorker
:真正的写入动作执行者,在writeCharacteristic()
方法中,终于看到
characteristic.setValue(value != null ? value : ByteUtils.EMPTY_BYTES);
调用原生的接口,写入了一个特征值
BluetoothGattResponse
:继承自原生的蓝牙写入回调,在BluetoothLEGatt连接的时候传入,然后写入成功后会收到回调。