Design Converter
Education
Last updated on Sep 4, 2024
Last updated on Sep 4, 2024
In every Android or iOS application, there are a few important processes that keep running in the background without asking the user to open the application. Some examples of such services that can be executed from the background while the app remains closed are:
Well, in the context of Flutter, until now the application can only handle the background events using the platform code. Any plugins had no way to allow users to make a callback for handling the background events in Dart.
That is the reason why Flutter users need to create platform-specific implementations for handling background events in the application.
So, how will you schedule an application task/service when the user isn’t focused on it, especially when Android 8.0 (API Level 26) imposes some restrictions on what app could be run in the background?
However, recently Flutter started supporting the background execution of Dart code. Let’s explore more about the android background services and available options in Flutter that can help Android developers manage Flutter background services.
But before going deep into the details of Android background services first, understand some basics of the background services in Android.
An app or a service is said to be running in the background if it satisfies the following conditions:
The background services fall into three categories:
All these background services can be persistent or impersistent:
The following table will help you to decide on the approach you should take for each kind of background service.
For scheduling the background events Android and iOS follow very different approaches. With Android, there are various ways to schedule the Background services, few of the popular ways are,
In the case of iOS applications, the number of available options is much more limited. Its system decides when to allow an app to perform background fetch so that the application seems to remain alive. Also, it may decide to never start an app for performing background fetch.
Now let’s look into each approach in detail.
Geofencing is nothing but using a virtual geographical boundary around the physical location. It enables users to detect when someone enters or leaves the location. It helps trigger events and notifications in real-time.
To implement Geofencing in the Flutter application use flutter_geofence, a plugin for all your geofence interactions. It is compatible with both Android and iOS platforms.
Installation:
Run the following command
1 flutter pub add flutter_geofence
This will add the following dependencies to your pubspec.yaml file.
1 dependencies: 2 flutter_geofence: ^0.4.4 3
Importing to dart code.
1 import 'package:flutter_geofence/Geolocation.dart'; 2 import 'package:flutter_geofence/geofence.dart'; 3
Example: Using Geofence to get current location
The following command provides you Future that resolves with the current Coordinate of the user. If there is one that's recent enough (< 60 seconds old), it'll return to this location.
1 Geofence.getCurrentLocation().then((coordinate) { 2 print("Your latitude is ${coordinate.latitude} and longitude ${coordinate.longitude}"); 3 }); 4
Alarms are a special use case that does not come under the background work. Alarm managers are used to scheduling the exact alarm such as alarm clocks or calendar events.
When used to schedule background work it wakes the device from Dzone mode and thus may have a negative impact on the battery life and overall system health.
A Flutter plugin android_alarm_manager_plus is used for accessing the Android Alarm Mangerservicesand running Dart code in the background when the Alarm is fired.
Installation:
Run the following command
1 flutter pub add android_alarm_manager_plus
This will add the following dependencies to your pubspec.yaml file.
1 dependencies: 2 android_alarm_manager_plus: ^2.0.6 3
Importing to the Dart code.
1 import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart'; 2
Example:
Here printHello will then run after every minute, even if the main app ends. However, it will not run in the same isolate as the main application. Because it doesn't share memory and communication between isolates must be done via message passing.
1 import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart'; 2 3 static void printHello() { 4 final DateTime now = DateTime.now(); 5 final int isolateId = Isolate.current.hashCode; 6 print("[$now] Hello, world! isolate=${isolateId} function='$printHello'"); 7 } 8 9 main() async { 10 // Be sure to add this line if initialize() call happens before runApp() 11 WidgetsFlutterBinding.ensureInitialized(); 12 13 await AndroidAlarmManager.initialize(); 14 runApp(...); 15 final int helloAlarmID = 0; 16 await AndroidAlarmManager.periodic(const Duration(minutes: 1), helloAlarmID, printHello); 17 } 18
If you want to schedule a service it should be defined in the Job Service. The service is invoked for the tasks that are scheduled to be run depending on the system condition.
It enables the system to perform your work regardless of if your app is active or idle. Also, you can write multiple Job services, where each one defines a different task, this helps you to modularise your code.
For scheduling any Job Service you shall need to add this to the one of your AndoridManifest.xml.
1<service 2 android:name=".sync.DownloadArtworkJobService" 3 android:permission="android.permission.BIND_JOB_SERVICE" 4 android:exported="true"/> 5
It adds permission that will allow the Job Scheduler to call your jobs and be the only one that accesses your JobService.
The Firebase JobDispacher is the Library for scheduling background jobs in the Android app. It provides a JobShedular-Compatible API that works on all the latest versions of Android (API level 9+) that have Google Play services installed.
However, with the introduction of the Android Jetpack WorkManager, the developer team decided to deprecate the Firebase JobDispacher and focus completely on the WorkManager. The new Work Manager works with or without the Google Play Services, which FJD cannot do.
Work Manager - A new job management system in the Jetpack that incorporates the features of both Firebase JobDispacher and JobScheduler to provide consistent job scheduling services back to API level 14 and leverages the JobScheduler on the new devices.
Android WorkManger is a background processing library that is used to schedule and run background tasks, in a guaranteed way but not necessarily immediately. With it, the user can enqueue background processing even when the app is not running and the device is rebooted.
A Flutter work Manager plugin is a wrapper around the Android’s WorkManger, iOS’ performFetchWithCompletionHandler, and iOS BGAppRefreshTask, effectively enabling headless execution of the Dart code in the background.
Installation
Run the command given below.
1 flutter pub add workmanager
This will add the following line to your pubspec.yaml file.
1 dependencies: 2 workmanager: ^0.5.0 3
To import the plugin in the main.dart file adds the line below.
1 import 'package:workmanager/workmanager.dart';
Example:
The work manager must be initialized before registering any task.
1 void callbackDispatcher() { 2 Workmanager().executeTask((task, inputData) { 3 print("Native called background task: $backgroundTask"); //simpleTask will be emitted here. 4 return Future.value(true); 5 }); 6 } 7 8 void main() { 9 Workmanager().initialize( 10 callbackDispatcher, // The top level function, aka callbackDispatcher 11 isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks 12 ); 13 Workmanager().registerOneOffTask("task-identifier", "simpleTask"); 14 runApp(MyApp()); 15 } 16
Here the callbackDispacher needs to be either a static function or a top-level function that can be accessible as a Flutter entry point.
In the post, you have learned about the Android background services and the effective ways to manage them in the Flutter applications.
If you are developing an Android or iOS app with Flutter try using DhiWise to speed up the app development process. The LowCode/ ProCode platform aims to reduce repetitive tasks in application development without compromising the code quality.
It is a multi-technology platform that supports various technologies and frameworks so that developers can build any application with the tech stack they love.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.