Flutter - 前台服务停止蓝牙/BLE 连接

问题描述 投票:0回答:1

当应用程序从后台恢复时,例如锁定屏幕并恢复或移动到其他应用程序并返回,使用 flutter_reactive_ble 库连接的 BLE 设备会自动断开连接。 因此,我检查了我的代码,发现当应用程序恢复时,我的后台服务将停止。 iOS 没有问题,只有安卓有问题。

这是我的蓝牙连接代码。

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

这是我的后台服务代码。

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

使用此代码,当应用程序从后台恢复时,首先调用 service.stopSelf() 函数。然后 print("BLE Disconnect 已断开");函数被调用。

我也尝试过https://pub.dev/packages/flutter_background_service但我得到了同样的错误......

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

请给我一个解决方案。谢谢你。

android flutter dart bluetooth-lowenergy foreground-service
1个回答
0
投票

直到我明白

@pragma('vm:entry-point')
仅在应用程序终止时才起作用(完全关闭)

如果您在应用程序从后台重新启动后尝试重新连接(如果可能),请尝试此操作。

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print("app in resumed");
        break;
      case AppLifecycleState.inactive:
        print("app in inactive");
        break;
      case AppLifecycleState.paused:
        print("app in paused");
        break;
      case AppLifecycleState.detached:
        print("app in detached");
        break;
    }
}

一旦您从 backStake 收到再次激活的应用程序,您就可以使用您的代码。 检查连接性,然后通过 BLE 连接到设备。

就我而言,我正在使用相同的做法,并且它对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.