我正在尝试在 Flutter 和 Android 之间创建一个通道。
我在 MainActivity 中有这段代码,当从 FLutter 代码调用时,这个通道工作正常。
setMethodCallHandler { call, result ->
Log.d("configureFlutterEngine", "${call.method} $result $call")
if (call.method == "getBatteryLevel") {
val batteryLevel = getBatteryLevel()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else if (call.method == "startTrackingService") {
Log.d("startTrackingService", "calling foregroundService()")
foregroundService()
result.success(true)
} else if (call.method == "stopTrackingService") {
Log.d("stopTrackingService", "calling stopTrackingService()")
stopTrackingService()
result.success(true)
} else {
result.notImplemented()
}
}
但它不能以另一种方式工作,即原生到 FLutter。我在我的 android 服务 onCreate() 中有这段代码。
FlutterLoader().apply {
startInitialization(context)
ensureInitializationComplete(context, arrayOfNulls(0))
val engine = FlutterEngine(context.applicationContext)
val entrypoint = DartEntrypoint.createDefault()
engine.dartExecutor.executeDartEntrypoint(entrypoint)
methodChannel = MethodChannel(engine.dartExecutor.binaryMessenger, "android-flutter")
每次我获得位置时都会调用它。
methodChannel?.invokeMethod("getTracking", position.toJson(), object: MethodChannel.Result {
override fun success(result: Any?) {
Log.d("success", result.toString())
}
override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) {
Log.d("error", errorDetails.toString())
}
override fun notImplemented() {
Log.d("notImplemented", "notImplemented".toString())
}
})
}
我在 Flutter Widget 中有这个。
void initState() {
super.initState();
MethodChannel("android-flutter").setMethodCallHandler((call) async {
Fimber.i("$call invoked");
if (call.method == "getTracking") {
if (call.arguments is String) {
Fimber.i(call.arguments);
Position position = Position.fromJsonString(call.arguments);
Fimber.i(position.toString());
}
} else {
throw MissingPluginException();
}
return true;
});
}
在服务内部调用了invokeMethod(...),但没有调用flutter中的方法定义。每次调用服务中的invokeMethod()后,Result(){}下覆盖的notImplemented()方法是被叫。