I have implemented background_fetch with the purpose of sending a notification every 15 minutes, independently whether the app is in foreground, background or even terminated. Therefore I have enabled the headless task and I expect that the task is run every 15 minutes as set in the configuration. Unfortunately the task is not run reiably every 15 Minutes but more or less randomly timed. Sometimes it is way more than 15 minutes, sometimes less.
I am writing the Datetime into a file when the notification is called and therefore when the background task is executed. My code:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:background_fetch/background_fetch.dart';
const String darwinNotificationCategoryPlain = 'plainCategory';
var flutterLocalNotificationsPlugin;
const BigPictureStyleInformation bigPictureStyleInformation =
BigPictureStyleInformation(FilePathAndroidBitmap(filePath));
// [Android-only] This "Headless Task" is run when the Android app is terminated with `enableHeadless: true`
// Be sure to annotate your callback function to avoid issues in release mode on Flutter >= 3.3.0
@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
String taskId = task.taskId;
bool isTimeout = task.timeout;
if (isTimeout) {
// This task has exceeded its allowed running-time.
// You must stop what you're doing and immediately .finish(taskId)
print("[BackgroundFetch] Headless task timed-out: $taskId");
BackgroundFetch.finish(taskId);
return;
}
print('[BackgroundFetch] Headless event received.');
await displayDefaultNotification(flutterLocalNotificationsPlugin);
BackgroundFetch.finish(taskId);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
// Initialize settings for Android and iOS (optional)
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
const DarwinInitializationSettings iosInitializationSettings =
DarwinInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
final InitializationSettings initializationSettings = InitializationSettings(
android: androidInitializationSettings,
iOS: iosInitializationSettings,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
);
// final NotificationAppLaunchDetails? notificationAppLaunchDetails =
// await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
// print(notificationAppLaunchDetails!.payload)
await checkForNotificationPermission();
displayDefaultNotification(flutterLocalNotificationsPlugin);
// displayDefaultNotification(flutterLocalNotificationsPlugin);
runApp(MyApp());
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}
class _MyHomePageState extends State<MyHomePage> {
var selectedIndex = 0;
bool _enabled = true;
int _status = 0;
List<DateTime> _events = [];
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
// Configure BackgroundFetch.
int status = await BackgroundFetch.configure(
BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
startOnBoot: true,
requiredNetworkType: NetworkType.NONE), (String taskId) async {
// <-- Event handler
// This is the fetch-event callback.
print("[BackgroundFetch] Event received $taskId");
setState(() {
_events.insert(0, DateTime.now());
});
print(_events);
await displayDefaultNotification(flutterLocalNotificationsPlugin);
// IMPORTANT: You must signal completion of your task or the OS can punish your app
// for taking too long in the background.
BackgroundFetch.finish(taskId);
}, (String taskId) async {
// <-- Task timeout handler.
// This task has exceeded its allowed running-time. You must stop what you're doing and immediately .finish(taskId)
print("[BackgroundFetch] TASK TIMEOUT taskId: $taskId");
BackgroundFetch.finish(taskId);
});
print('[BackgroundFetch] configure success: $status');
setState(() {
_status = status;
});
BackgroundFetch.start();
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
}
@override
void initState() {
super.initState();
initPlatformState();
}
@override
Widget build(BuildContext context) {...}
}
The notification Times for Pixel 4a5G with Android 14
2024-07-29 15:05:26.877718
2024-07-29 15:23:20.991382
2024-07-29 15:36:05.143673
2024-07-29 16:02:08.090906
2024-07-29 16:21:14.200182
2024-07-29 16:41:00.026499
2024-07-29 16:53:05.973345
2024-07-29 17:12:14.996613
2024-07-29 17:28:07.996494
2024-07-29 18:32:45.126085
2024-07-29 20:33:15.997699
2024-07-30 00:33:48.249979
2024-07-30 06:34:19.821947
2024-07-30 07:14:54.260683
2024-07-30 07:20:28.538866
2024-07-30 07:26:29.551641
2024-07-30 07:38:38.554131
2024-07-30 07:57:44.502563
2024-07-30 08:17:31.533179
2024-07-30 09:18:13.508133
2024-07-30 11:18:44.663900
2024-07-30 13:58:40.824553
2024-07-30 14:08:38.899333
2024-07-30 14:25:24.406585
2024-07-30 14:56:36.743304
2024-07-30 15:16:28.221726
2024-07-30 16:17:10.223297
2024-07-30 18:17:41.181456
2024-07-30 22:18:12.241528
2024-07-31 07:53:34.376777
2024-07-31 07:55:29.126301
and Pixel 7a with Android 14:
2024-07-29 15:08:14.310578
2024-07-29 15:29:58.152395
2024-07-29 15:42:27.513763
2024-07-29 16:11:03.303112
2024-07-29 16:11:10.865647
2024-07-29 16:31:07.227808
2024-07-29 17:02:43.977619
2024-07-29 17:11:03.108158
2024-07-29 18:01:07.133911
2024-07-29 18:01:25.880473
2024-07-29 18:10:15.912472
2024-07-29 18:23:44.941566
2024-07-29 18:54:43.265052
2024-07-29 19:13:32.752487
2024-07-29 19:33:35.077056
2024-07-29 19:38:34.337924
2024-07-29 20:51:21.117066
2024-07-29 20:55:18.387087
2024-07-29 21:08:13.029925
2024-07-29 21:35:02.060821
2024-07-29 21:38:59.288287
2024-07-29 22:14:31.977626
2024-07-29 22:23:36.359301
2024-07-29 22:38:14.280385
2024-07-29 22:53:22.365538
2024-07-29 23:09:35.449230
2024-07-29 23:26:31.630029
2024-07-29 23:40:00.112814
2024-07-29 23:55:59.577659
2024-07-30 00:09:00.145944
2024-07-30 00:24:00.097036
2024-07-30 00:42:00.182504
2024-07-30 00:54:38.865178
2024-07-30 01:10:00.199837
2024-07-30 01:25:24.511933
2024-07-30 01:41:00.194125
2024-07-30 01:54:00.138022
2024-07-30 02:09:00.1456
Pabart13 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.