BackgroundFetch class
BackgroundFetch API
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.
iOS
There is no way to increase the rate which a fetch-event occurs on iOS and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
Android
The Android plugin provides an BackgroundFetchConfig.enableHeadless mechanism allowing you to continue handling events even after app-termination (see BackgroundFetchConfig.enableHeadless).
BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15, // <-- minutes
stopOnTerminate: false,
startOnBoot: true
), (String taskId) async { // <-- Event callback
// This callback is typically fired every 15 minutes while in the background.
print('[BackgroundFetch] Event received.');
// IMPORTANT: You must signal completion of your fetch task or the OS could
// punish your app for spending much time in the background.
BackgroundFetch.finish(taskId);
}, (String taskId) async { // <-- Task timeout callback
// This task has exceeded its allowed running-time. You must stop what you're doing and immediately .finish(taskId)
BackgroundFetch.finish(taskId);
})
Custom Tasks
In addition to the default periodic task that executes according to the configured minimumFetchInterval, you may also execute your own custom "oneshot" or "periodic" tasks using the method scheduleTask:
Note: All scheduled tasks are fired into the callback Function provided to the configure method.
⚠️ iOS:
scheduleTaskon iOS seems only to run when the device is plugged into power.scheduleTaskon iOS are designed for low-priority tasks, such as purging cache files — they tend to be unreliable for mission-critical tasks.scheduleTaskwill never run a frequently as you want.- The default
fetchevent is much more reliable and fires far more often.
BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
forceAlarmManager: true
), (String taskId) async { // <-- Event callback
print("[BackgroundFetch] taskId: $taskId");
switch (taskId) {
case 'com.foo.customfetchtask':
// Handle your custom task here.
break;
default:
// Handle the default periodic fetch task here///
}
// You must call finish for each taskId.
BackgroundFetch.finish(taskId);
}, (String taskId) async { // <-- Task timeout callback
// This task has exceeded its allowed running-time. You must stop what you're doing and immediately .finish(taskId)
BackgroundFetch.finish(taskId);
});
// Task will be executed by Callback provided to #configure, see switch(taskId) above.
BackgroundFetch.scheduleTask(TaskConfig(
taskId: "com.foo.customtask",
delay: 60000, // milliseconds
periodic: false
));
Android-only: forceAlarmManager: true:
By default, the plugin will use Android's JobScheduler when possible. The JobScheduler API prioritizes for battery-life, throttling task-execution based upon device usage and battery level.
Configuring forceAlarmManager: true will bypass JobScheduler to use Android's older AlarmManager API, resulting in more accurate task-execution at the cost of higher battery usage.
BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
forceAlarmManager: true
), (String taskId) async { // <-- Event callback
print("[BackgroundFetch] taskId: $taskId");
BackgroundFetch.finish(taskId);
}, (String taskId) async { // <-- Timeout callback
// This task has exceeded its allowed running-time. You must stop what you're doing and immediately .finish(taskId)
BackgroundFetch.finish(taskId);
});
BackgroundFetch.scheduleTask(TaskConfig(
taskId: 'com.foo.customtask',
delay: 5000, // milliseconds
forceAlarmManager: true
periodic: false
));
Constructors
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
configure(
BackgroundFetchConfig config, Function onFetch, [Function? onTimeout]) → Future< int> -
Configures the plugin's BackgroundFetchConfig and
callbackFunction. Thiscallbackwill fire each time a background-fetch event occurs (typically every 15 min). -
finish(
String taskId) → Future< void> -
Signal to the OS that your fetch-event for the provided
taskIdis complete. -
registerHeadlessTask(
Function callback) → Future< bool> - Android-only: Registers a global function to execute when your app has been terminated.
-
scheduleTask(
TaskConfig config) → Future< bool> - Schedule a background-task to occur in TaskConfig.delay milliseconds.
-
start(
) → Future< int> - Start the background-fetch API.
-
stop(
[String? taskId]) → Future< int> - Stop the background-fetch API from firing events.
Constants
- FETCH_RESULT_FAILED → const int
- See finish. An attempt to download data was made but that attempt failed.
- FETCH_RESULT_NEW_DATA → const int
- See finish. New data was successfully downloaded.
- FETCH_RESULT_NO_DATA → const int
- See finish. There was no new data to download.
- STATUS_AVAILABLE → const int
- See status. Background updates are available for the app.
- STATUS_DENIED → const int
- See status. The user explicitly disabled background behavior for this app or for the whole system.
- STATUS_RESTRICTED → const int
- See status. Background updates are unavailable and the user cannot enable them again. For example, this status can occur when parental controls are in effect for the current user.