How to create a background task in fluent

Time:2022-5-16

How to create a background task in fluent

original text

https://www.dltlabs.com/blog/…

reference resources

text

Today, I will explain how to create a background task in fluent.

Before that, let’s understand what background tasks are. A background task is a worker process of an application running in the background, even if the application is not running or in a terminated state.

This feature is useful for applications that need to perform tasks in the background without the user opening the application. For example, call the API every 15 minutes to obtain data.

Let’s implement a background task in a sample project to better understand the meaning of this operation.

Steps:

  • pubspec.yaml
flutter pub add background_fetch
flutter pub get
  • In main Import the background package into the dart file and register the headlesstask to receive the backgroundfetch event after the application terminates.

For example:

void backgroundFetchHeadlessTask(HeadlessTask task) async {var taskId = task.taskId;
if(taskId == ‘your_task_id’) {
print(‘your_task_id’);
print(‘[BackgroundFetch] Headless event received.’);
_//TODO: perform tasks like — call api, DB and local notification etc…
_}
}
void main() {
runApp(MyApp());
_//Registering backgroundFetch to receive events after app is terminated.
// Requires {stopOnTerminate: false, enableHeadless: true}
_BackgroundFetch._registerHeadlessTask_(backgroundFetchHeadlessTask);
}

Here we have to pass a top-level function. Let’s be hereregisterHeadlessTaskMethodcall back dispatcher。 Then we define the tasks that need to run in the background:

Configure backgroundfetch

Future<void> initPlatformState() async {
_// Configure BackgroundFetch.
_var status = await BackgroundFetch._configure_(BackgroundFetchConfig(
minimumFetchInterval: 15,
forceAlarmManager: false,
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.NONE,
), _onBackgroundFetch, _onBackgroundFetchTimeout);
print(‘[BackgroundFetch] configure success: $status’);
_// Schedule backgroundfetch for the 1st time it will execute with 1000ms delay.
// where device must be powered (and delay will be throttled by the OS).
_BackgroundFetch.scheduleTask(TaskConfig(
taskId: “com.dltlabs.task”,
delay: 1000,
periodic: false,
stopOnTerminate: false,
enableHeadless: true
));
}

callinitStateMediuminitPlatformStateMethod and setBackgroundFetchConfigClass configuration. In other words, the option to register a one-time task or a recurring task is provided while passing other parameters.

Here, if there are multiple tasks, the task ID can help us easily identify a single task. The input data can be any information needed to process the task.

If we want to continue working while the application is in a terminated state, pleasestopOnTerminateThe value of the parameter is set tofalse。 IfstopOnTerminateSet totrue, the background service will terminate when the application terminates.

void _onBackgroundFetchTimeout(String taskId) {
print(“[BackgroundFetch] TIMEOUT: $taskId”);
BackgroundFetch.finish(taskId);
}

Called when the operating system does not execute the background task or the task cannot run within a given timeonBackgroundFetchTimeoutmethod. In this method, we can use the task ID to process the task.

void _onBackgroundFetch(String taskId) async {
if(taskId == ‘your_task_id’) {
print(‘[BackgroundFetch] Event received’);
//TODO: perform your task like : call the API’s, call the DB and local notification.
}
}

Called when the background service executes an eventonBackgroundFetchmethod. In this method, we take the received task ID as a parameter, which can be used to process the task. This is important when you need to call an API to save data to a database or display local notifications.

By default, the frequency of the time interval after the task is invoked is 15 minutes. If you want to set it to something else, you can also do it here. On Android, the minimum interval between background processes is 15 minutes. If the value is less than 15, Android uses 15 minutes by default.

Also, we must also remember to make changes inside the info.plist and manifest.xml file for both iOS \& Android. We need to set some of the permissions, and we also need to copy and paste other settings. If you need these settings, you can get them at the following links: Android , OS.

In addition, we must also remember the importance of Android IOSinfo.plistandmanifest.xmlMake changes to the file. We need to set some permissions and copy and paste other settings. If you need these settings, you can get them through the following link:IOS , Android

Thank you for reading!


© Cat brother

How to create a background task in fluent