PhilipsHue / flutter_reactive_ble

Flutter library that handles BLE operations for multiple devices.
https://developers.meethue.com/
Other
661 stars 321 forks source link

Automatically disconnect when background service stop #852

Open JinZhuXing opened 5 months ago

JinZhuXing commented 5 months ago

BLE device which was connected using flutter_reactive_ble library disconnect automatically when the app restored from background, such as lock screen and restore or move to other app and return. So, I checked my code and noticed that when the app restored, my background service will be stopped. There is no problem in iOS, only in android.

This is my bluetooth connect code.

deviceStream = flutterReactiveBle
    .connectToDevice(
        id: device.id, connectionTimeout: const Duration(seconds: 5))
    .listen(
  (connectionState) {
    if (connectionState.connectionState ==
        DeviceConnectionState.connected) {
      // connected process
    } else if (connectionState.connectionState ==
        DeviceConnectionState.disconnected) {
      print("BLE Disconnect is disconnected");
      onDisconnect(index, true);
    }
  },
  onError: (error) {
    print("BLE Disconnect connection error = $error");
  },
);

This is my background service code.

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();
  // FlutterReactiveBle flutterReactiveBle = FlutterReactiveBle();

  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });
    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
      // print('dolphine $event');
    });
  }
  service.on('stopService').listen((event) {
    service.stopSelf();
  });
}

With this code, when the app restored from background, first service.stopSelf() function is called. And then print("BLE Disconnect is disconnected"); function is called.

Please give me a solution. Thank you.

Naografix commented 4 months ago

Same issue here... I don't understand why when I call "service.stopSelf()" my bluetooth disconnect... Do you find a solution @JinZhuXing ?

Thanks

JinZhuXing commented 4 months ago

I didn't yet. Still waiting.