javaandroidflutterdart

Run a headless Dart/Flutter callback on receiving a notification in Android


I am developing a Flutter app that listens to notifications and processes them in a specific manner.

I was using the notifications package to receive the notifications directly in my Flutter code, avoiding the platform implementation, but it didn't work in the background. The flutter_background package enabled the app to remain active while minimized; however, it didn't work when the user terminated the app or after a prolonged period of inactivity.

The Geofencing example on writing background isolates appears to be outdated, as many Java classes are now deprecated.

I tried to create WorkManager tasks that would initialize the Flutter engine and run a callback that listens to messages on the method channel when notifications are received. However, the Workers cannot create a FlutterEngine instance, as that can only be done on the main thread.

How can I create a Flutter Engine and pass data to it from the background thread?


Solution

  • I've found the flutter_background_task package, which does exactly what I wanted to implement.

    It runs a user-defined Dart callback on a separate isolate in a background thread, that continues executing even if the app is closed by the user or the device is restarted.

    And it also fulfils my main request - the notification listener can be started and run as usual in that callback.