flutter_ble Android 设备蓝牙BLE 无法断开重新问题

安卓设备断开后重新总是报错,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 disconnect() {
    return _device.disconnect().then((value) => _clearResources());
  }

Future _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 无法断开重新问题)