gpt4 book ai didi

android - 如何从 Android 服务调用 Dart 代码?

转载 作者:行者123 更新时间:2023-12-03 02:41:27 24 4
gpt4 key购买 nike

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

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

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

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

我检查了 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
  • 关于android - 如何从 Android 服务调用 Dart 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61347243/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com