flutter_background_service
flutter_background_service copied to clipboard
Stop service once the app is closed
Is it possible to stop this service once the user closes the app?
I am building a timer and I am setting the setForegroundMode
to true
in order to show the notification.
Once the user has closed the app I need to end all of the background processes.
Is it possible to create a method similar to setForegroundMode
that we can call when we initialize the service that will kill the background process once the app is closed?
An alternative would be to add a service.appIsRunning
function that would return a bool whenever the app is closed or running so we can add this check on every iteration of the timer. And if the app is closed we can just run stopBackgroundService()
service is part of the application, which means the service will not run without the application running.
If what you mean is to check whether there is an activity or UI running, it is not currently available. To stop the service, you can use the stopBackgroundService()
command
The service does not stop after I close the app. I have tested this in development and with a real apk. Cound this be somehow related to the fact that I am building a timer and I have an interval running? @ekasetiawans
service.onDataReceived.listen((event) {
if (event["action"] == "startStopwatch") {
service.setForegroundMode(true);
_stopwatchTime = event["time"] != null ? event["time"] : 0;
timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
_stopwatchTime++;
service.setNotificationInfo(
title: event["title"],
content: "$_stopwatchTime",
);
service.sendData(
{"current_date": _stopwatchTime},
);
});
}
});
The purpose of this background service is to continue executing code behind the scenes even though the application is closed. If you want to execute code only when the app is active, you can use isolate.
Isolates are paused when the app is open but goes into background.
You can close the issue if you think this functionality does not belong to this service.
As an alternative, is it possible to add click events on the notification so we can open the app on a specific route if it is closed (or open) ? Or just open the app in general, otherwise we have a non-removable and non-clickable notification that just hangs @ekasetiawans
@zommerberg Did you found anything? Looking for similiar thing?
I made two timers. One is in the application, the other is in the service. I send data from the application to the service. If the application stops sending data, then I stop the service.