Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Flutter background service that works also when app closed

I am developing a Flutter app for academic purposes in university. Now, I need to run a sort of "always on" background service in order to use Bluetooth and most importantly to get periodic updates from external REST APIs.

I've already checked those two libraries from pub.dev (this and this) without finding the perfect solution that works out-of-the-box (as expected...). I also saw something native with Kotlin (here). What I would to know is what is the best option in order to achieve my goals (in terms of best practices, completeness and with simplicity in mind).

Have a look at the following image for a more schematic view:

enter image description here

like image 806
docdev Avatar asked Jun 04 '20 15:06

docdev


People also ask

Does Flutter timer run in background?

Please note: This timer only runs when the app is running - it does not schedule anything to be run in the background using OS-specific scheduling mechanisms, nor does it attempt to wake the device or app.

How do I use background fetch in Flutter?

Flutter background_fetch Background Fetch is a very simple plugin which will awaken an app in the background about every 15 minutes, providing a short period of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs.


3 Answers

Can I run Dart code in the background of an Flutter app?

Yes, you can run Dart code in a background process on both iOS and Android. For more information, see the Medium article Executing Dart in the Background with Flutter Plugins and Geofencing.

Credit to Raouf Rahiche

like image 137
Christopher Moore Avatar answered Oct 22 '22 07:10

Christopher Moore


For this kind of things you have to rely on native mechanisms.

The most efficient way to deal with APIs in an "always existent" background component is to implement a push notification service. Using that kind of tech a remote server is capable of starting communication with your app, awaken it and then perform whatever task needs to be performed.

Also, in Android, you have foreground services which will run even if the app is closed.

like image 36
svprdga Avatar answered Oct 22 '22 07:10

svprdga


You might want to have a look at flutter_background_service package. It helps executing Dart code in the background.

like image 8
Jago Avatar answered Oct 22 '22 06:10

Jago