蓝牙订阅事件异常,主要分为以下三类场景:
例如,使用access.on('stateChange', this.onReceiveEvent)订阅蓝牙设备开关状态事件后,使用方式一可以正常取消订阅,而使用方式二却无法取消订阅。
function onReceiveEvent(data: access.BluetoothState) {
console.info(`bluetooth state = ${data}`);
}
// 订阅蓝牙设备开关状态事件
access.on('stateChange', this.onReceiveEvent)
// 方式一,取消订阅正常
access.off('stateChange');
// 方式二,无法取消订阅
access.off('stateChange', (callback: access.BluetoothState) => {
console.info('蓝牙开关取消订阅')
}); 例如,订阅on('BLECharacteristicChange')后,server端特征值内容变更通知client端,但未触发回调。
例如,使用access.on('stateChange')订阅蓝牙设备开关状态事件后关闭蓝牙,会接收到多次蓝牙已关闭的状态。
// 方式二正确写法
access.off('stateChange', this.onReceiveEvent); 