original
https://www.dltlabs.com/blog/flutter-run-code-in-the-background-513940
refer to
text
Today, I will explain how to create a background task in Flutter.
Before that, let's understand what background tasks are. A background task is a worker process for an application that runs in the background, even if the application is not running or is in a terminated state.
This feature is beneficial for applications that need to perform tasks in the background without requiring the user to open the application — for example, calling an API every 15 minutes to get data.
Let's implement a background task in a sample project to better understand what this operation means.
step:
- pubspec.yaml
flutter pub add background_fetch
flutter pub get
- Import the background package in the main.dart file and register the HeadlessTask to receive backgroundFetch events 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 name it call back dispatcher
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 initState
in initPlatformState
method and set BackgroundFetchConfig
class configuration. In other words, provide the option to register a one-time task or a recurring task while passing other parameters.
Here, if there are multiple tasks, the task id can help us to easily identify a single task. 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, set the value of the stopOnTerminate
false
. If stopOnTerminate
set to true
, the background service will be terminated when the application terminates.
void _onBackgroundFetchTimeout(String taskId) {
print(“[BackgroundFetch] TIMEOUT: $taskId”);
BackgroundFetch.finish(taskId);
}
onBackgroundFetchTimeout
method is called when the operating system is not executing a background task or the task cannot run within the given time. In this method, we can use the taskId 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.
}
}
onBackgroundFetch
method is called when the background service executes the event. In this method, we will receive the task id as a parameter, which can be used to process the task. This is very important in situations such as calling an api to save data to a database or display a local notification.
By default, the frequency of the interval after calling the task is 15 minutes. If you want to set it to something else, you can do it here too. On Android, the minimum 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.
Also, we have to remember to make changes to info.plist
and manifest.xml
We need to set some permissions and also copy and paste other settings. If you need these settings, you can get them from the following links: IOS , Android .
Thanks for reading!
© Cat Brother
- WeChat ducafecat
- Blog ducafecat.tech
- github
- bilibili
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。