Flutter Android Alarm Manager not working

2020-06-23 08:56发布

问题:

I have installed the Android Alarm Manager plugin in my Flutter v1.0.0 app by following the instructions at the link. But when I try to use AndroidAlarmManager.oneShot(...) nothing happens. There's not even an error in the console.

I am using a FutureBuilder widget to wait on the AndroidAlarmManager.initialize() future and one other future before my app begins rendering:

final combinedFutures = Future.wait<void>([
  gameService.asyncLoad(),
  AndroidAlarmManager.initialize(),
]);

FutureBuilder<void>(
  future: combinedFutures,
  builder: (context, snapshot) {
    ...
  }
)

The FutureBuilder does end up rendering what it should so I know that the AndroidAlarmManager.initialize() future returns correctly.

Then in a button's onPressed function I do this:

AndroidAlarmManager.oneShot(
  Duration(seconds: 5),
  0,
  () {
    print("test");
  },
  wakeup: true,
);

The above should be calling print(test) after 5 seconds and waking up my phone but nothing is printed to the console and nothing happens on my phone. What is going wrong?

回答1:

After debugging the library code I found that the AndroidAlarmManager.oneShot function calls the method PluginUtilities.getCallbackHandle(callback) where callback is the function passed in. In my case the callback function was:

() {
  print("test");
}

For some reason PluginUtilities.getCallbackHandle was returning null when it should be returning a value of type CallbackHandle.

Looking at the PluginUtilities.getCallbackHandle documentation it says:

Get a handle to a named top-level or static callback function which can be easily passed between isolates.

The function I was passing is not top-level, static, or named. So I did the following inside my class and everything works fine now:

static void alarmTest() {
  print("test");
}

void runAlarm() {
  AndroidAlarmManager.oneShot(
    Duration(seconds: 10),
    0,
    alarmTest,
    wakeup: true,
  ).then((val) => print(val));
}


标签: dart flutter