美文网首页
flutter_ble Android 设备蓝牙BLE 无法断开

flutter_ble Android 设备蓝牙BLE 无法断开

作者: 一抹远方 | 来源:发表于2021-09-24 13:07 被阅读0次

    安卓设备断开后重新总是报错,iOS无此问题,困扰一个月时间,光顾了各大网站无解,其实作者早已给出答案。

    https://github.com/pauldemarco/flutter_blue/issues/525
    connect() method:

    void connect(BluetoothDevice device) async {
        await _device.connect(autoConnect: false);
    
        _stateSubscription = _device.state.listen((state) async {
          if (state == BluetoothDeviceState.disconnected) {
            await _stateSubscription.cancel();
            _stateSubscription = null;
          }
    
          if (state == BluetoothDeviceState.connected) {
            _mtuSubscription = _device.mtu.listen((mtu) async {
              await notifyCharacteristic.setNotifyValue(true);
            });
    
            _servicesSubscription = _device.services.listen((services) async {
              var service = services.first;
              notifyCharacteristic = service.characteristics.firstWhere((c) => c.uuid.toString().toUpperCase() == TX_NOTIFY_CHARACTERISTIC_UUID);
              writeCharacteristic = service.characteristics.firstWhere((c) => c.uuid.toString().toUpperCase() == RX_WRITE_CHARACTERISTIC_UUID);
    
              _notifySubscription = notifyCharacteristic.value.listen((value) {
                //Proceed with data...
              });
              _device.requestMtu(PREFERRED_MTU_SIZE);
            });
    
            _device.discoverServices();
          }
        });
      }
    
    

    disconnect() method

    Future<void> disconnect() {
        return _device.disconnect().then((value) => _clearResources());
      }
    
    Future<void> _clearResources() async {
        await _mtuSubscription.cancel();
        _mtuSubscription = null;
        await _servicesSubscription.cancel();
        _servicesSubscription = null;
        await _notifySubscription.cancel();
        _notifySubscription = null;
        notifyChannel = null;
        writeChannel = null;
      }
    
    

    相关文章

      网友评论

          本文标题:flutter_ble Android 设备蓝牙BLE 无法断开

          本文链接:https://www.haomeiwen.com/subject/ziqzgltx.html