回顾
需要参考学习BLE通信的可以看看之前的博客: 使用Android插件形式进行BLE开发(读写)
微信小程序——Ble之notify通信
微信小程序开发----BLE蓝牙通信(读写)
notify通信
扫描、连接、开启服务等操作,和之前的使用Android插件形式进行BLE开发(读写)保持一致。
再开启通信服务 成功之后,需要在此处开启notify 数据监听操作。当监听开启成功,则需要在gatt回执 中的onCharacteristicChanged 获取数据变化监听。
开启notify监听操作,采取如下方式:
在通信服务 开启成功后,执行下列操作即可。
public boolean openBleNotify(String serviceUUID, String characteristicUUID,String descriptUUID) {
boolean isOpen = false;
if (mBluetoothGatt != null && getConnectedState() == BluetoothProfile.STATE_CONNECTED) {
BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString(serviceUUID));
if(service != null) {
BluetoothGattCharacteristic gattCharacteristic = service
.getCharacteristic(UUID.fromString(characteristicUUID));
if(gattCharacteristic != null) {
BluetoothGattDescriptor descriptor = gattCharacteristic.getDescriptor(UUID.fromString(descriptUUID));
if(descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
isOpen = mBluetoothGatt.setCharacteristicNotification(gattCharacteristic, true);
}
}
}
return isOpen;
}
调用时,只需要传递下列参数信息:
boolean isOpenBleNotify = openBleNotify(BleLockPeroties.wrAndReService_uuid,
BleLockPeroties.read3_infa_chara_uuid,
BleLockPeroties.descript_uuid2);
本次使用的各项参数如下所示:
public static final String wrAndReService_uuid = "0000ccd0-0000-1000-8000-00805f9b34fb";
public static final String read3_infa_chara_uuid = "0000ccd1-0000-1000-8000-00805f9b34fb";
public static final String descript_uuid1 = "00002901-0000-1000-8000-00805f9b34fb";
public static final String descript_uuid2 = "00002902-0000-1000-8000-00805f9b34fb";
注意
- 1、连接成功之后,不要立马进行服务开启操作。
- 2、notify监听服务开启成功后,不要立即执行发送命令操作。
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Log.i("定时开启服务--->", "延迟发送开锁指令");
SENDBLEDATA();
}
}, delaySendOpenCodeTimes);
|