装修公司网站模版第三方推广平台
flutter开发实战-MethodChannel实现flutter与原生Android双向通信
最近开发中需要原生Android与flutter实现通信,这里使用的MethodChannel
一、MethodChannel
MethodChannel:用于传递方法调用(method invocation)。
通道的客户端和宿主端通过传递给通道构造函数的通道名称进行连接
一个应用中所使用的所有通道名称必须是唯一的
使用唯一的域前缀为通道名称添加前缀,比如:samples.flutter.dev/battery
官网 https://flutter.cn/docs/development/platform-integration/platform-channels
https://blog.csdn.net/gloryFlow/article/details/132218837
二、在flutter端实现MethodChannel
我们需要创建一个名字为"samples.flutter.dev/test"的通道名称。
通过invokeNativeMethod与setMethodCallHandler来实现
- invokeNativeMethod:调用Android端的代码
- setMethodCallHandler:设置方法回调,用于接收Android端的参数
代码如下
import 'package:flutter/services.dart';//MethodChannel
const methodChannel = const MethodChannel('samples.flutter.dev/test');class FlutterMethodChannel {/** MethodChannel* 在方法通道上调用方法invokeMethod* methodName 方法名称* params 发送给原生的参数* return数据 原生发给Flutter的参数*/static Future<Map> invokeNativeMethod(String methodName,[Map? params]) async {var res;try {if (params == null) {res = await methodChannel.invokeMethod('$methodName');} else {res = await methodChannel.invokeMethod('$methodName', params);}} catch (e) {res = {'Failed': e.toString()};}return res;}/** MethodChannel* 接收methodHandler* methodName 方法名称* params 发送给原生的参数* return数据 原生发给Flutter的参数*/static void methodHandlerListener(Future<dynamic> Function(MethodCall call)? handler) {methodChannel.setMethodCallHandler(handler);}
}使用该MethodChannel,我们需要使用MethodChannel
使用代码如下void initState() {// TODO: implement initStatesuper.initState();setMethodHandle();}void setMethodHandle() {FlutterMethodChannel.methodHandlerListener((call) {print("methodHandlerListener call:${call.toString()}");if ("methodToFlutter" == call.method) {print("methodToFlutter arg:${call.arguments}");}return Future.value("message from flutter");});}Future<void> invokeNativeMethod() async {var result = await FlutterMethodChannel.invokeNativeMethod("methodTest", {"param":"params from flutter"});print("invokeNativeMethod result:${result.toString()}");}void testButtonTouched() {invokeNativeMethod();}void dispose() {// TODO: implement disposesuper.dispose();}
这里我们处理了方法methodToFlutter来接收Android端的传参数调用,同时处理后我们将结果"message from flutter"返回给Android端。
我们调用Android端的方法methodTest,并且传参,获取Android端传回的结果。
三、在Android端MainActivity
在Android的MainActivity中,同样我们实现了MethodChannel
设置setMethodCallHandler及调用Flutter的方法
代码如下
import android.util.Log;import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;import java.util.Timer;
import java.util.TimerTask;public class MainActivity extends FlutterActivity {private MethodChannel methodChannel;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);getMethodChannel().setMethodCallHandler((call, result) -> {if (TextUtils.equals(call.method, "methodTest")) {result.success("message from Android");} else {result.error("1", "Illegal Argument Exception", "Unsupported Method - " + call.method);}});new Timer().schedule(new TimerTask() {@Overridepublic void run() {runOnUiThread(() -> {getMethodChannel().invokeMethod("methodToFlutter", "Params from Android");});}}, 10 * 1000);}private MethodChannel getMethodChannel() {if (methodChannel == null) {methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor(), "samples.flutter.dev/test");}return methodChannel;}
}
我们在Android的MainActivity中通过调用方法methodToFlutter将参数传递给Flutter端。设置setMethodCallHandler根据方法methodTest处理接收来自flutter的参数,处理后并将结果返回给flutter。
注意:在MainActivity中调用Timer,需要在主线程中调用,可以使用runOnUiThread来处理。
四、小结
flutter开发实战-MethodChannel实现flutter与原生Android双向通信。实现MethodChannel在flutter端与Android端的MainActivity的实现相互通信功能。
学习记录,每天不停进步。