How to create a background task in fluent

Posted by rookie on Thu, 20 Jan 2022 07:36:48 +0100

original text

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

reference resources

text

Today, I'll 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 function 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 must pass a top-level function. Let's name it call back dispatcher in the registerHeadlessTask method. 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
));
}

Call the initPlatformState method in initState and set the configuration of the BackgroundFetchConfig class. 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 the terminated state, set the value of the stopOnTerminate parameter to false. If stopOnTerminate is set to true, the background service will terminate when the application terminates.

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

When the operating system does not execute the background task or the task cannot run within a given time, the onBackgroundFetchTimeout method is called. 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.
}
}

When the background service executes the event, the onBackgroundFetch method is called. 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 time interval for 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 info for Android IOS Plist and manifest XML 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

Topics: Flutter