Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically disconnect when background service stop #852

Open
JinZhuXing opened this issue Mar 14, 2024 · 2 comments
Open

Automatically disconnect when background service stop #852

JinZhuXing opened this issue Mar 14, 2024 · 2 comments

Comments

@JinZhuXing
Copy link

JinZhuXing commented Mar 14, 2024

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.

@Naografix
Copy link

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

Thanks

@JinZhuXing
Copy link
Author

I didn't yet. Still waiting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants