flutter_ble Android 設備藍牙BLE 無法斷開重新問題

安卓設備斷開后重新總是報錯,iOS無此問題,困擾一個月時間,光顧了各大網(wǎng)站無解,其實作者早已給出答案。

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;
  }

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容