这段时间一直在进行手机与BLE的相关项目开发,其中对读数据、写数据、接收通知消息、接收指示型消息这几种操作有了一些了解,今天贴出来跟大家分享一下。(关于蓝牙的搜索,连接,获取服务,获取特征值等方法这里就不再赘述了,网上很多前辈总结的很全面,可以自行搜索。
这几个操作的共同特性都是通过调用回调方法进行数据的获取和交换,所以进行相关操作之前熟悉每个操作相关的回调方法是很有必要的。
1.接收通知消息(setCharacteristicNotification):
前期进行BLE开发或许很容易混淆读操作和接收通知消息,这里我按自己的理解粗糙的讲解一下。通知是BLE终端主动或是相关操作触发而发出的数据,任何一个用于权限的主机都可以读取到这个数据。
而读操作时谁进行读数据操作,然后BLE终端才会被动的发出一个数据,而这个数据只能是读操作的对象才有资格获得到这个数据。
//首先必须获取通知通道(这里的UUID根据自己BLE终端,自己进行读取操作获得)
service = mBluetoothGatt.getService(uuid_s);
characteristic = service.getCharacteristic(uuid_c);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(uuid_d);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
mBluetoothGatt.setCharacteristicNotification(characteristic, true);
//然后重写回调方法,跟根据通知数据的类型进行解析操作,判断是否接收到通知利用Log日志可以观察到。
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.i(TAG, "onCharacteristicChanged!");
//进行接收数据的相关操作
String data = characteristic.getValue();
}
super.onCharacteristicChanged(gatt, characteristic);
}
2.读数据(readCharacteristic):
读数据,顾名思义是对BLE进行读取数据的操作,这个数据
//首先获取读数据相关的通道
service = mBluetoothGatt.getService(uuid_s);
characteristic = service.getCharacteristic(uuid_c);
mBluetoothGatt.readCharacteristic(characteristic);
3.写数据(readCharacteristic):
if (mBluetoothGatt != null){
if (characteristic != null){
characteristic.setValue(data);
mBluetoothGatt.writeCharacteristic(characteristic);
Log.i(TAG, "writeData:写了一次数据!");
}
}
4.指示(readCharacteristic):
//获取指示通道
characteristic = service.getCharacteristic(uuid2_c_n);
if (characteristic != null){
BluetoothGattDescriptor descriptor = characteristic_notify.getDescriptor(uuid_d);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
Log.i(TAG, "Descriptor write: " + mBluetoothGatt.writeDescriptor(descriptor));
mBluetoothGatt.setCharacteristicNotification(characteristic , true);
}
}
以上几种操作都需要对应的uuid,uuid的值一般对应的蓝牙工程会在接口文档中给出,我们按照文档进行相关的操作。——一篇在草稿中躺了两年的博客,还是发出来日后温习一遍把。