Is it posible to run dart code in platform-specific Android Service with Flutter?

Viewed 445

I have a Flutter library that work well in Flutter main.dart but I need to use it in Android services to run in background.

Since Flutter hasn't support Services yet (as I know), so I create a native Android Service using Java and start it using MethodChannel. But I don't know how to use the Flutter library inside my Service.

So is it possible to use the Flutter library inside Android Service or I need to convert the library to Java code?

I already researched Isolate, Background processes and Geofencing but they are not 100% same as Service.

Update

Actually, after open a foreground service, Android will keep the app running in the background. So open the service and display a Notification is all I need to do, no need to put more code in the service.

1 Answers

It's possible using MethodChannel but instead of invoking from dart and handling it in native platform, you should handle calls in dart and invoke from native platform. In dart you're gonna have something like this:

MethodChannel _methodChannel = MethodChannel('bridge');
_methodChannel.setMethodCallHandler((call) {
  doSomething();
});

And in your service in android platform you will invoke a method on the same channel:

MethodChannel(flutterEngine.dartExecutor.binaryMessenger, 'bridge').invokeMethod('method', argument)
Related