Android蓝牙开发流程

149 阅读2分钟

一、传统蓝牙

1、配置权限

<uses-permission android:name=”android.permission.BLUETOOTH”/>

<!-- 扫描蓝牙设备或操作蓝牙设置 -->

<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>

<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>

<uses-permission android:name=”android.permission.ACCESS_FIND_LOCATION/>

2、使用BluetoothAdapter.getDefaultAdapter()获取BluetoothAdapter对象,若为null表示设备不支持蓝牙,否则可以执行BluetoothAdapter.getBondedDevices()获取已配对的设备集合,并异步调用startDiscovery()开始设备扫描。通过注册广播接收扫描状态和结果,保存扫描到的设备BluetoothDevice对象。

3、通过反射调用BluetoothDevice类中的createBond()进行设备配对,配对成功后可以调用BluetoothAdapter.cancelDiscovery()关闭扫描。

4、异步调用BluetoothDevices.createRfcommSocketToServiceRecord()开始连接,获取到BluetoothSocket对象进行蓝牙通信。

二、BLE

1、权限

// Android 12之下:

<uses-permission android:name="android.permission.BLUETOOTH"/>

<uses-permission android:name="android.permission.ACCESS_FIND_LOCATION"/>

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

// Android 12以上:

<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>

2、调用getDefaultAdapter()获取BluetoothAdapter对象,若为null表示不支持蓝牙,否则通过BluetoothAdapter获取BluetoothLeScanner对象,然后创建ScanCallback接口对象,用于处理扫描结果,并且可以创建多个ScanFilter对象,执行setDeviceName()setServiceUuid()setDeviceAddress()等,配置需要查找的设备信息。把ScanFilter对象添加到集合中,与ScanCallback对象一起传入到BluetoothLeScanner.startScan()开始设备扫描。

3、在ScanCallback.onScanResult()中扫描到需要的设备后,通过ScanResult获取BluetoothDevice对象,然后创建BluetoothGattCallback接口对象传递给BluetoothDevice.connectGatt()进行Gatt链接。

4、在BluetoothGattCallback.onConnectionStateChange()中state的值为BluetoothGatt.GATT_SUCCESS和newState的值为BluetoothProfile.STATE_CONNECTED,表示Gatt链接成功后,执行BluetoothGatt.discoverServices()搜索Gatt服务。

5、当BluetoothGattCallback.onServiceDiscovered()内status值为BluetoothGatt.GATT_SUCCESS,成功发现Gatt服务后,将通信使用的Service UUID 传递给BluetoothGatt.getService()获取到BluetoothGattService对象,然后使用对应的UUID分别匹配找到用于消息监听和发送的BluetoothGattCharacteristic对象。

6、将消息监听的BluetoothGattCharacteristic对象传递到BluetoothGatt.setCharacteristicNotification()boolean参数设置为true,然后对BluetoothGattCharacteristic对象的BluetoothGattDescriptor集合对象进行遍历,每个对象执行setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE),并传递到BluetoothGatt.writeDescriptor(),进行消息通知注册。当接收到外部设备的蓝牙数据,在Android 11以下的设备中,会回调BluetoothGattCallBack.onCharacteristicChanged(BluetoothGatt, BluetoothGattCharacteristic),否则会回调onCharacteristicChanged(BluetoothGatt, BluetoothGattCharacteristic, ByteArray)

7、把需要发送给蓝牙设备的Byte数组数据赋值给消息发送的BluetoothGattCharacteristic对象中的value对象,然后传递给与设备链接的BluetoothGatt对象的writeCharacteristic()进行消息发送。

参照:

blog.csdn.net/u010356768/…

mp.weixin.qq.com/s/QlFK5cAAo…

mp.weixin.qq.com/s/3nwlVB00l…