一.前言
Andorid 5.0 之前是无法进行 外围设备开发的,在Android 5.0 API 21 android.bluetooth.le包下,新增加 Scaner相关类和 Advertiser 相关类。目前最后使用Scanner相关类实现蓝牙扫描。这段时间对蓝牙的学习与理解,对中心设备与周边设备做下面总结。
android.bluetooth.le

1.
2.
3.BlueToothDevice#connectGatt()
如果你对 Central 与 Peripheral 理解的话,就移步下面文章 !
Android 5.0 BLE 实现中心与外围设备 (待更…)
二. Central 和 Peripheral
1. 蓝牙通信规则
CentralPeripheral客户端-服务端结构。
Peripheral客户端(中心设备):
CentralPerpheral如下图所示,心跳监听器提供心跳数据,在你的其他设备的app上 需要以用户友好的方式显示用户的心跳信息。

2.Central 发现并连接广播中的 Peripheral
在BLE中 ,PeripheralCentral提供数据是主要方式。主要操作如下:
- 服务端 外围设备(
Peripheral): 向外广播数据包(Advertising)形式的数据,比如设备名称,功能等! - 客户端 中心设备(
Central
如图所示 :

例如 :
温度传感器设备会向外广播它获取到的温度信息
3. 外围设备(Peripheral
PeripheralService(服务)以及有关其连接信号强度的有用信息 。
ServiceCharacteristic)。Characteristicvalue和0至多个对次value的描述(Descriptor),知道更多数据细节。Descriptor
如图所示:

三. Central 与 Peripheral 交互总结
CentralPerpheraldiscoverServices)PerpheralServices和CharacteristicCentralService中的Characteristicvalue与Perpheral进行交互。
以Android 开发举例 :
I . Central (中心设备)开发流程
建立中心角色
确定中心角色,客户端确立。扫描 外设
BluetoothAdapter#startLeScan()android.bluetooth.leBluetoothLeScaner#startScan()实现。建立连接
BluetoothGattBlueToothDevice#connectGatt()获取services与characteristics
在连接设备的时候,会使用BluetoothGattCallbackdiscoverservices@Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothGatt.STATE_CONNECTED) { gatt.discoverServices(); } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); //当调用 discoverServices的时候,会调用此方法 printServices(gatt); }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
Characteristic断开连接
代码如下:public void disconnect() { if (mBluetoothGatt != null) { mBluetoothGatt.disconnect(); mBluetoothGatt.close(); } }- 1
- 2
- 3
- 4
- 5
- 6
II . Peripheral(外围设备)开发流程
确定外围设备
初始化外围设备管理对象
BluetoothLeAdvertiserBluetoothAdapter#getBluetoothLeAdvertiser()打开外围广播
根据SERIVE_UUID,打开一个外围设备连接,通过下面类实现BluetoothLeAdvertiser#startAdvertising();获取外围设备
Server
通过BluetoothGattServermBluetoothManager.openGattServer(mContext, bluetoothGattServerCallback)
四.参考文档
https://developer.android.google.cn/reference/android/bluetooth/le/AdvertiseData.html
