flutter_reactive_ble icon indicating copy to clipboard operation
flutter_reactive_ble copied to clipboard

Automatically disconnect when background service stop

Open JinZhuXing opened this issue 11 months ago • 2 comments

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.

  • System: Android
  • Flutter Version: 3.16.7
  • Package Versions: flutter_reactive_ble: v5.3.1 flutter_background_service : v5.0.5

Please give me a solution. Thank you.

JinZhuXing avatar Mar 14 '24 07:03 JinZhuXing