【问题标题】:Flutter how to discovering bluetooth devices in background (flutter_bluetooth_serial)Flutter 如何在后台发现蓝牙设备(flutter_bluetooth_serial)
【发布时间】:2020-06-22 11:08:28
【问题描述】:

我想在后台开始连续搜索蓝牙设备,并在检测到设备“X”时发送通知。

此时我每 5 秒运行一次定期计时器,在此期间我执行新的扫描

即使我关闭了应用程序,我该如何进行此扫描?

  Timer.periodic(Duration(milliseconds: 5000), (timer) => discovery());

  void discovery() {
    var tmp = new Map<String, BluetoothDevice>();

    FlutterBluetoothSerial.instance.startDiscovery().listen((r) {
      tmp.putIfAbsent(r.device.address, () => r.device);

      app.onDiscovery(r);
    }).onDone(() {
      _isDiscovering = false;
    });
  }

我想要一个兼容 IOS 和 Android 的解决方案。

谢谢你,美好的一天。

【问题讨论】:

  • 据我所知,FlutterBluetoothSerial 与 iOS BLE (Bluetooth 4.0 +) 设备不兼容。因为它主要与蓝牙2.0的HC-5兼容。关于后台任务,您可以使用其他一些 pkg 'flutter_beacon' 来实现,它具有内置流式'监控,用于后台跟踪。

标签: android ios flutter dart bluetooth


【解决方案1】:

要在后台运行任务,您可能需要考虑使用Isolate

Isolate? isolate;

@override
void initState() {
  /// Start background task
  _asyncInit();
  super.initState();
}


_asyncInit() async {
  final ReceivePort receivePort = ReceivePort();
  isolate = await Isolate.spawn(_isolateEntry, receivePort.sendPort);

  receivePort.listen((dynamic data) {
    if (data is SendPort) {
      if (mounted) {
        data.send({
          /// Map data using key-value pair
          /// i.e. 'key' : String
        });
      }
    } else {
      if (mounted) {
        setState(() {
          /// Update data here as needed
        });
      }
    }
  });
}

static _isolateEntry(dynamic d) async {
  final ReceivePort receivePort = ReceivePort();
  d.send(receivePort.sendPort);

  /// config contains the key-value pair from _asyncInit()
  final config = await receivePort.first;
 
  /// send bluetooth data you received
  d.send(...);
}

@override
void dispose() {
  /// Determine when to terminate the Isolate
  if (isolate != null) {
    isolate.kill();
  }
  super.dispose();
}

至于 Flutter 对 BLE 的支持,你也可以考虑使用flutter_blue

【讨论】:

    猜你喜欢
    • 2015-01-26
    • 1970-01-01
    • 2012-04-19
    • 2017-03-17
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多