Android 蓝牙难点总结

Android 蓝牙难点4.0总结

基础请看蓝牙官方文档https://developer.android.google.cn/guide/topics/connectivity/bluetooth.html

//初始化ble设配器

private void initBle() {

        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

        bluetoothAdapter = manager.getAdapter();

    }

// 实现扫描回调接口

implements BluetoothAdapter.LeScanCallback

两种方式本身实现或new 一个新class

扫描回调

bluetoothAdapter.startLeScan(this/leScanCallback)
// 扫描到新设备时,会回调该接口。

public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {}

返回的有蓝牙设备、无线接收信号强度(RSSI)、广播包

byte[] scanRecord数据如下图:

可根据 https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ /蓝牙官网协议文档进行解析

如果知道要扫描的设备的serviceUUID 可以通过Android sdk 自身的方法进行扫描。

public boolean startLeScan(UUID[] serviceUuids, LeScanCallback callback) {

// 连接蓝牙设备,device为之前扫描得到的

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

使用BluetoothGattCallback 来跟设备进行通信

低功耗蓝牙(BLE)设备的通信基本协议是 GATT, 要操作 BLE 设备,第一步就是要连接设备,其实就是连接 BLE 设备上的 GATT service。

// 实现连接回调接口[关键]

class BleGattCallback extends BluetoothGattCallback {

会继承以下几个关键方法

// 连接状态改变(连接成功或失败)时回调该接口

mBluetoothGatt是连接完成时的对象,调用这句后,会走回调函数的onServicesDiscovered方法。在这个方法中去获取设备的一些服务,蓝牙通道,然后通过这些通道去发送数据给外设。

在蓝牙设备中, 其包含有多个BluetoothGattService, 而每个BluetoothGattService中又包含有多个BluetoothGattCharacteristic。

获取到设备中的服务列表  mBluetoothGatt.getServices(); 或者通过uuid 来获取某一个服务。

通过Gatt这个对像,就是蓝牙连接完成后获取到的对象,通过这个对象设置好指定的通道向设备中写入和读取数据。

    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {}

        // status 用于返回操作是否成功,会返回异常码。

        // newState 返回连接状态,

public void onServicesDiscovered(BluetoothGatt gatt, int status) {}

public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

//数据在这里接收

final byte[] data = characteristic.getValue();

根据蓝牙协议进行数据解析

}

public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {}

public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {}

public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {}

做通信要已知设备的通信协议,Service_UUID,Characteristic_UUID_WRITE,Characteristic_UUID_NOTIFY,如果多通道的话,要监听所有通道,否则数据丢失,没办法对接收到的数据进行解析。

发送指令:监听UUID_WRITE,

BluetoothGattCharacteristic write = gattService

                .getCharacteristic(Characteristic_UUID_WRITE);

将byte[]写入特征

  write.setValue(value);

通过gatt传递写特征gatt.writeCharacteristic(write);

发布了71 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39131246/article/details/103845641