I've created app that checks the call log list every 15 seconds. I have used Timer.periodic() to achieve this. And everything works fine but only if app is not running in the background. After couple of minutes when app is in the background, the task which is scheduled by Timer.periodic is not executing anymore. I have tried to use android_alarm_manager https://pub.dev/packages/android_alarm_manager but it doesn't work at all. It's logging /FlutterBackgroundExecutor(11431): Starting AlarmService... but then nothing happends.
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:android_alarm_manager/android_alarm_manager.dart';
void main() async{
await WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
runApp(MyApp());
final int helloAlarmID = 0;
await AndroidAlarmManager.periodic(Duration(seconds: 5), helloAlarmID, printHello);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
void printHello() {
final DateTime now = DateTime.now();
final int isolateId = Isolate.current.hashCode;
print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");
}
Do I have any other possibilities to reach my goal ?
Android limits background usage to every 15 minutes or so. There are several packages on pub.dev that can run code in background even when the application is closed. However i don't think any of them can run your code every 15 seconds.
Packages include:
background_fetch
workmanager
flutter_background_service
There are several more.