0

I am trying to run a piece of dart code when the android device boots up. Ideally, the code should run immediately or with a small delay (1-2 minutes at most). I don't want the app to start up, just a headless piece of code to run.

My Use Case:

I am working on an alarm clock application, and I want to handle the alarms that go off when the device is turned off, like disabling one-time alarms, and scheduling the next alarm if it's a repeat alarm. I can't afford to wait for long to handle these cases in case a repeat alarm was scheduled to ring shortly after the user boots up the device.

What I Have Tried:

I have tried doing it with flutter_background_fetch, with headless: true and startOnBoot: true. But it runs the code at 15 minutes intervals, which is too long for my use case, as explained above.

Ahsan Sarwar
  • 23
  • 1
  • 4

1 Answers1

2

So I finally figured it out. I first found this great article, Initiating calls to Dart from the native side in the background, detailing how to call dart code from native side while the app was in the background. This was only one piece of the puzzle though, as I had to figure out how to do so from a BroadcastReceiver. Luckily, I realized that android_alarm_manager_plus did something similar. So using code from those two resources, I managed to get it working.

The code is available at flutter_boot_receiver along with the instructions on how to use it.

Details on how it works

  1. Sends a dart callback handle to the native side, where it gets stored in the SharedPreferences.
  2. Specifies a BootReceiver, which listens for the BOOT_COMPLETED event. This event is fired by the android system whenever the device boots.
  3. When the BootReceiver receives the event, it starts a JobIntentService.
  4. The service creates a background FlutterEngine and a method channel to communicate with the dart code.
  5. It then retrieves the dart callback handle from the SharedPreferences and sends it to the dart side via the method channel.
  6. The dart side then retrieves the callback from the handle and then calls it.

Notes

  1. The callback runs in an isolate, so can't access data initialized in your main dart isolate. You can use dart packages/plugins though. Just be sure to initialize them in the isolate if necessary.
  2. Some device might not receive the BOOT_COMPLETED event. You can find more info here. Consider creating an issue in the repo if that is the case.
Ahsan Sarwar
  • 23
  • 1
  • 4