Run a background task with android_alarm_manager in flutter

Viewed 3439

I'm trying to use the android_alarm_manager plugin in flutter to run a simple background task periodicly. I followed the instructions from the readme file and it kind of worked but not properly..

I sticked to the example and firstly created a periodicly task that prints a message every minute. After I run a hotstart for the app, I recived this message to the console:

W/AlarmService( 4261): Attempted to start a duplicate background isolate. Returning...

So I tried to cancel the task and create a new one that runs every 5 seconds. But that did not work out. Though the cancel method returns true, the first task is still running every minute and not every 5 seconds like intendet.

Performing hot restart...

Syncing files to device AOSP on IA Emulator...

W/AlarmService( 4261): Attempted to start a duplicate background isolate. Returning...

Restarted application in 2.194ms.

I/AlarmService( 4261): AlarmService started!

I/flutter ( 4261): [2020-07-24 06:21:34.697305] Hello, world! isolate=531288143

I/flutter ( 4261): [2020-07-24 06:22:34.635681] Hello, world! isolate=531288143

I/flutter ( 4261): [2020-07-24 06:23:52.208643] Hello, world! isolate=531288143

I/flutter ( 4261): [2020-07-24 06:25:14.658737] Hello, world! isolate=531288143

I/flutter ( 4261): [2020-07-24 06:26:14.703225] Hello, world! isolate=531288143

I/flutter ( 4261): [2020-07-24 06:27:14.728071] Hello, world! isolate=531288143

I/flutter ( 4261): [2020-07-24 06:28:14.760309] Hello, world! isolate=531288143

This is the code I'm using. When I execute it the first time, I gave the id 0 to the task that runs every minute. So I tried to cancel this id and create a new one after initialize.

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await AndroidAlarmManager.cancel(0);
    await AndroidAlarmManager.initialize();
    runApp(TimeReminder());
    await AndroidAlarmManager.periodic(const Duration(seconds: 5), 0, printHello);
}

void printHello() {
   final DateTime now = DateTime.now();
   final int isolateId = Isolate.current.hashCode;
   print("[$now] Hello, world! isolate=$isolateId");
}

Does anyone know how to fix this? Or in general can anyone explain this to me? Is there a possibility to get an overview about all the tasks I have set?

Thanks in advance!

1 Answers

Since you are using an interval below 1 minute, your issue might be a system limitation. According to this comment:

Since Android 5.1, the minimum interval for a periodic fire using AlarmManager is 1 minute. So even if you pass a smaller duration, it will default to 1 minute. If you want to call more frequently, you should look into Handler.

Related