如何使用Flutter在后台服务通知上显示动态变化的值?

2sbarzqh  于 2023-03-24  发布在  Flutter
关注(0)|答案(1)|浏览(145)

我试图在后台服务通知上显示从BLE扫描的值,即使应用程序关闭。所以我使用[flutter_background_service] 1然而,我不知道如何显示动态变化的值,因为它显示在小部件上。我遇到了麻烦。.我可以寻求您的帮助吗?谢谢。

Timer.periodic(const Duration(seconds: 1), (timer) async {
    if (service is AndroidServiceInstance) {
      if (await service.isForegroundService()) {
        /// OPTIONAL for use custom notification
        /// the notification id must be equals with AndroidConfiguration when you call configure() method.
        flutterLocalNotificationsPlugin.show(
          888,
          'App Name',
          'value: ${}, // <- I want to put value in here.
          const NotificationDetails(
            android: AndroidNotificationDetails(
              'my_foreground',
              'MY FOREGROUND SERVICE',
              icon: 'ic_bg_service_small',
              ongoing: true,
            ),
          ),
        );
      }
    }
py49o6xq

py49o6xq1#

首先创建一个新类。

class ProjectBackgroundService{}

现在让我们定义您将在这个类中使用的函数。
第一个是**readyForShared()**函数。该函数允许我们定义和读取局部变量。

`Future<void> readyForShared() async {
   var sharedPreferences = await SharedPreferences.getInstance();
   counterValue = sharedPreferences.getString("yourVariable") ??"0";
 }`

现在让我们编写保存局部变量的函数。

Future<void> saveData(String value) async {
  var sharedPreferences = await SharedPreferences.getInstance();
  sharedPreferences.setString("yourVariable", value);
}

现在让我们编写服务函数onStart()

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {

  // Only available for flutter 3.0.0 and later
  DartPluginRegistrant.ensureInitialized();

  // For flutter prior to version 3.0.0
  // We have to register the plugin manually

  SharedPreferences preferences = await SharedPreferences.getInstance();
  await preferences.setString("hello", "world");

  /// OPTIONAL when use custom notification
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    service.stopSelf();
  });
    
  // bring to foreground
  Timer.periodic(const Duration(seconds: 1), (timer) async {
    final receivePort = ReceivePort();
    // here we are passing method name and sendPort instance from ReceivePort as listener
    await Isolate.spawn(computationallyExpensiveTask, receivePort.sendPort);

    if (service is AndroidServiceInstance) {
      if (await service.isForegroundService()) {
        //It will listen for isolate function to finish
         receivePort.listen((sum) {
         flutterLocalNotificationsPlugin.show(
         888,
         'Title',
         'Description ${DateTime.now()}',
         const NotificationDetails(
         android: AndroidNotificationDetails(
         'my_foreground',
         'MY FOREGROUND SERVICE',
         icon: 'ic_bg_service_small',
         ongoing: true,
         ),
         ),
         );
         });

        var sharedPreferences = await SharedPreferences.getInstance();
        await sharedPreferences.reload(); // Its important
        service.setForegroundNotificationInfo(
          title: "My App Service",
          content: "Updated at ${sharedPreferences.getString("yourVariable") ?? 'no data'}",
        );
      }
    }

    /// you can print
    //if (kDebugMode) {
    //}

    // test using external plugin
    final deviceInfo = DeviceInfoPlugin();
    String? device;
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfo.androidInfo;
      device = androidInfo.model;
    }

    if (Platform.isIOS) {
      final iosInfo = await deviceInfo.iosInfo;
      device = iosInfo.model;
    }
    service.invoke(
      'update',
      {
        "current_date": '400',
        "device": device,
      },
    );
  });
}

现在让我们呼叫我们的服务

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
      readyForShared();
      ProjectBackgroundService().onStart();
    });
  }

相关问题