androidflutterflutter-dependenciesbackground-serviceflutter-background

How can I update the existing service from flutter background service?


I'm adding a few details (maximum 3) to my shared preferences. Additionally, I have a background service. Whenever a new detail is added to the shared preferences, I call the background service. However, when I add the second set of details, it is not fetched by the background service.

I want to update the background service with my latest shared preference, but I can see this in the console: 'V/BackgroundService(7959): Service already running, using existing service.' It seems like it is just running with the existing details and not picking up the new ones.

Can someone help me with a solution, like how I can update the service with my latest details? Below is my code for your reference. Thanks!

I'm using the flutter_background_service 5.0.5 package


//This is the screen I'm initialize background service inside my saveDetails
@override
void initState() {
  super.initState();
  Timer(const Duration(seconds: 5), () {
    if (mounted) {
      setState(() {
        enableOkayButton = true;
      });
    }
  });
  saveDetails();
}

//Here I'm adding detail in my shared preferences
Future<void> saveDetails() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int totalCount = prefs.getInt('idCount') ?? 0;
  int currentCount = totalCount + 1;
  prefs.setInt('idCount', currentCount);
  String key = 'TCID$currentCount';
  prefs.setString('$key-itemName', widget.name);
  prefs.setDouble('$key-amount', widget.amount);
  startService();
}


//This is my class where I had my background service class
Future<void> initializeService() async {
  final service = FlutterBackgroundService();

  await service.configure(
      iosConfiguration: IosConfiguration(),
      androidConfiguration: AndroidConfiguration(
          autoStart: true, onStart: onStart, isForegroundMode: true));
  service.startService();
}

@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();
  return true;
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  WidgetsFlutterBinding.ensureInitialized();
  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();
    });
  }
  Timer.periodic(const Duration(seconds: 5), (timer) async {
    if (service is AndroidServiceInstance) {
      if (await service.isForegroundService()) {
        service.setForegroundNotificationInfo(
          title: "My App Service",
          content: "Updated at ${DateTime.now()}",
        );
      }
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int totalCount = prefs.getInt('idCount') ?? 0;
    print("--------------------->Total idCount stored: $totalCount");
    // if (totalCount == 0) {
    //   service.stopSelf();
    //   return;
    // } else {
    for (int i = 1; i <= totalCount; i++) {
      String key = 'TCID$i';
      String nme = prefs.getDouble('$key-itemName') ?? 0.0;
      double amt = prefs.getString('$key-amount') ?? '';

      print('TCID $i:');
      print('  - Current Radius: $nme');
      print('  - Destination Title: $amt');
    }
    print("---------------------->Background task is running");
    // }
  });
}

I would like to update the existing service with my new details.


Solution

  • I also faced the same problem with shared preferences. So reloading shared preferences instance helped me solve this.

    final prefs = await SharedPreferences.getInstance();
    await prefs.reload();  //USE THIS
    

    Before setting/getting values in shared preference just use this one line. That will fetch latest stored local data in background service too.