How do I call Dart code from Android service?

I don't know how effective it is but it works :D

private static final String CHANNEL = "widget.filc.hu/timetable";
// You have to run this on the main thread, i think
public static MethodChannel GetMethodChannel(Context context) {
    FlutterMain.startInitialization(context);
    FlutterMain.ensureInitializationComplete(context, new String[0]);

    FlutterEngine engine = new FlutterEngine(context.getApplicationContext());


    DartExecutor.DartEntrypoint entrypoint = new DartExecutor.DartEntrypoint("lib/main.dart", "widget");

    engine.getDartExecutor().executeDartEntrypoint(entrypoint);
    return new MethodChannel(engine.getDartExecutor().getBinaryMessenger(), CHANNEL);
}

The dart side has an init function like this:

void widget() async {
    // get preferences everything what you want....
  
    await app.settings.update();
    // Create methodChannel
    const MethodChannel channel = MethodChannel(CHANNEL);
    channel.setMethodCallHandler(
     (call) async {
      final args = call.arguments;

      print('on Dart ${call.method}!');

      switch (call.method) {
      case 'getTimetable':
        return await _getTimetable();
      case 'getRandom':
        return Random().nextInt(100);
      case 'initialize':
        return "HELLO";
      default:
        throw UnimplementedError("Unknow: " + call.method);
    }
  },
);
}

These links are helped me:

  • Similar question,
  • Re-use a FlutterEngine