flutter_background_service icon indicating copy to clipboard operation
flutter_background_service copied to clipboard

How we can pass the init data to the service?

Open zamaniafshar opened this issue 2 years ago • 4 comments

Hello First of all thank you for creating this useful package.

So here is my problem: I have a timer app and when the user wants to close app i start foreground service and resume the timer in it. But for starting the timer from the previous duration in the foreground service i need to pass some data to it I know i can use on and invoke but there is a problem When the user close app very fastly i cant pass the init data

Here is the code:

 Future<void> startService(PomodoroTaskModel initData) async {
    await _service.startService();
    await _service.on('started').first;
    _service.invoke('initData', initData.toMap());
  }

void onForegroundServiceStart(ServiceInstance service) async {
  service.invoke('started');
  Map<String, dynamic>? initState = await service.on('initData').first;
}

How we can pass the init data to the service? I think it's will be so great if you get init data when we want to start the service Like this:

final initData={'duration':25};
FlutterBackgroundService().startService(initData);

and in the onForegroundServiceStart:

void onForegroundServiceStart(ServiceInstance service,Map initData) async {
  
}

Like this package https://pub.dev/packages/android_long_task

zamaniafshar avatar Oct 13 '22 16:10 zamaniafshar

Still no way to pass initial parameters on start? Duplicate #249

Heech avatar Apr 28 '23 08:04 Heech

Still no way to pass initial parameters on start? Duplicate #249

There is a way, but it's slow and time-consuming. In my specific case, I needed maximum speed for running a foreground service, so I wrote my own foreground service with Java. You can find the code here: https://github.com/zamaniafshar/sptimer.

I needed maximum speed because I run the foreground service when the user brings the app to pause mode, as I couldn't run the foreground service when the app is closed. However, if you don't need maximum speed and are okay with a 1-second delay for running the foreground service and getting initial data, you can use the above code, and it works fine.

zamaniafshar avatar Apr 28 '23 15:04 zamaniafshar

Has anyone been able to pass parameters to the onStart method?

msouzarunner avatar Jun 06 '23 13:06 msouzarunner

You can use shared preferences : shared_preferences: ^2.2.0 in somewhere on your app: final SharedPreferences sp = await SharedPreferences.getInstance(); sp.setString('token', body['data']['token']); in onStart: final SharedPreferences sp = await SharedPreferences.getInstance(); String? token = sp.getString('token'); debugPrint('Service=>Token : $token');

olcayergun avatar Jul 30 '23 05:07 olcayergun