我在Android中有一个后台服务,该服务使用以下代码在Flutter Dart代码中调用

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

我使用一个名为simple rsa的flutter库来加密位置。但是,Android似乎没有等效功能。所以,我的问题是:

我可以像使用Flutter MethodChannel一样从我的Android代码中调用Dart代码来调用Android代码吗?

我已经检查了this github问题,但是没有实际的答案。

最佳答案

我不知道它有多有效,但它有效: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);
}
Dart 端具有如下初始化函数:
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);
    }
  },
);
}
这些链接对我有帮助:
  • Similar question
  • Re-use a FlutterEngine
  • 09-25 22:28
    查看更多