本文将重点描述Android蓝牙GATT连接的大致流程,不会过多地纠缠代码细节,只为了从架构上梳理清楚,为接下来深入研究底层机制奠定一个宏观认识。
首先建立GATT连接前,我们通常要扫描蓝牙设备,获得设备的BluetoothDevice对象,然后调用connectGatt去建立GATT连接并等待连接状态回调,接下来我们就开始分析这一过程,首先看看connectGatt的实现:
public BluetoothGatt connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback, int transport) {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
IBluetoothManager managerService = adapter.getBluetoothManager();
try {
IBluetoothGatt iGatt = managerService.getBluetoothGatt();
if (iGatt == null) {
// BLE is not supported
return null;
}
BluetoothGatt gatt = new BluetoothGatt(context, iGatt, this, transport);
gatt.connect(autoConnect, callback);
return gatt;
} catch (RemoteException e) {Log.e(TAG, "", e);}
return null;
}
这里主要是获取IBluetoothGatt,Gatt相关操作是单独抽出来的,没有都塞到IBluetoothManager中,否则会让IBluetoothManager显得很臃肿,作为蓝牙总管IBluetoothManager还是简洁一些为好。这个IBluetoothGatt的真正实现在GattService中,不过在进入GattService之前,我们先看看这个BluetoothGatt的connect函数,这里为了突出重点略去了一些代码。
boolean connect(Boolean autoConnect, BluetoothGattCallback callback) {
if (!registerApp(callback)) {
return false;
}
return true;
}
这里只调用了registerApp,从字面意思上理解貌似与连接无关,只是注册一个调用方,我们看看其实现:
private boolean registerApp(BluetoothGattCallback callback) {
mCallback = callback;
UUID uuid = UUID.randomUUID();
try {
mService.registerClient(new ParcelUuid(uuid), mBluetoothGattCallback);
} catch (RemoteException e) {
return false;
}
return true;
}
这里给用户传进来的callback保存起来,生成了一个UUID作为调用方的标识,然后调用IBluetoothGatt的registerClient去注册,奇怪的是这里传入的是另外一个BluetoothGattCallback,这是个典型的静态代理,想必回调后还要做一些额外处理才会走到我们自己的callback。
private final IBluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallbackWrapper() {
public void