Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call Dart code from Android service?

I have a background service in Android that I call in my Flutter Dart code using

  var methodChannel = MethodChannel("org.daytonsquareroots.near.backgroundlocation");
    methodChannel.invokeMethod("startBackgroundService", {
      "encKey" : encryptionKey
    });

I use a flutter library called simple rsa to encrypt location. However, Android doesn't seem to have an equivalent. So, my question is:

Can I call Dart code from my Android code like I do with the Flutter MethodChannel to call Android code?

I have checked this github issue, but there are no actual answers that I can find.

like image 418
Friedrick Avatar asked Apr 21 '20 15:04

Friedrick


People also ask

How can I open Dart file in Android Studio?

First, create the MyFirstDartProject folder. Secondly, on Android Studio, open the folder you have just created. Then create a new file: File > New > File > MyFirstDart.

Where is the main Dart file in Android Studio?

Once you have created your project, you will see the “lib” folder where the “main. dart” file is located. Most importantly, once you have created a project and developed the application, Flutter expects the “main.


Video Answer


1 Answers

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
like image 132
T. Johnny Avatar answered Oct 26 '22 00:10

T. Johnny