flutter_background_service
flutter_background_service copied to clipboard
How we can pass the init data to the service?
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
Still no way to pass initial parameters on start? Duplicate #249
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.
Has anyone been able to pass parameters to the onStart method?
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');