Flutter how to discovering bluetooth devices in background (flutter_bluetooth_serial)

Viewed 2486

I would like to start a continuous search for bluetooth devices in the background and send a notification when a device "X" is detected.

At this moment I run a periodic timer every 5 seconds, in which I perform a new scan

How can I do this scan even if I turn off the application?

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

I would like a solution compatible with IOS and Android.

Thank you and good day.

1 Answers

To run tasks in the background, you may want to look into using 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();
}

As for BLE support on Flutter, you can also look into using flutter_blue

Related