Flutter与android原生通信

Flutter与android原生通信,第1张

概述 Flutter 与Android/iOS之间信息交互通过PlatformChannel进行桥接;Flutter 定义了三种不同的Channel;但无论是传递方法还是传递事件,其本质上都是数据的传递;MethodChannel:用于传递方法调用; EventChannel:用于数据流信息通信;BasicMessageChannel:用于传递字符串和半结构

 

Flutter 与 AndroID/iOS 之间信息交互通过 Platform Channel 进行桥接; Flutter 定义了三种不同的 Channel;但无论是传递方法还是传递事件,其本质上都是数据的传递;

MethodChannel:用于传递方法调用; EventChannel:用于数据流信息通信;BasicmessageChannel:用于传递字符串和半结构化的信息;

每种 Channel 均包含三个成员变量;

name:代表 Channe 唯一标识符,Channel 可以包含多个,但 name 为唯一的;messager:代表消息发送与接收的工具 BinaryMessenger;codec:代表消息的编解码器

1、MethodChannel:

Flutter代码:

// 调用原生方法static const methodChannel = const MethodChannel('Flutter_and_native_101');static Future<dynamic> invokNative(String method, {Map arguments}) async {  if (arguments == null) {    return await methodChannel.invokeMethod(method);  } else {    return await methodChannel.invokeMethod(method, arguments);  }}// 监听原生返回Future<dynamic> nativeMessageListener() async {    methodChannel.setMethodCallHandler((resultCall) {      MethodCall call = resultCall;      String method = call.method;      Map arguments = call.arguments;      int code = arguments["code"];      String message = arguments["message"];      setState(() {        recive += " code $code message $message and method $method \n";        print(recive);      });      return null;    });  }// 调用onpressed: () {    invokNative("test")    ..then((result) {        int code = result["code"];        String message = result["message"];        setState(() {        	recive = "invokNative 中的回调 code $code message $message ";        });    });}

androID代码:

private voID methodChannelFunction() {    mMethodChannel = new MethodChannel(getFlutterVIEw(), "Flutter_and_native_101");    //设置监听    mMethodChannel.setMethodCallHandler(            new MethodChannel.MethodCallHandler() {                @OverrIDe                public voID onMethodCall(MethodCall call, MethodChannel.Result result) {                    String lMethod = call.method;                    if (lMethod.equals("test")) {                        Toast.makeText(mContext, "Flutter 调用到了 androID test", Toast.LENGTH_SHORT).show();                        Map<String, Object> resultMap = new HashMap<>();                        resultMap.put("message", "result.success 返回给Flutter的数据");                        resultMap.put("code", 300);                        result.success(resultMap);                    } else if (lMethod.equals("test2")) {                        //Toast.makeText(mContext, "Flutter 调用到了 androID test", Toast.LENGTH_SHORT).show();                        Map<String, Object> resultMap = new HashMap<>();                        resultMap.put("message", "androID 主动调用 Flutter test 方法");                        resultMap.put("code", 301);                        mMethodChannel.invokeMethod("test", resultMap);                        mHandler.postDelayed(new Runnable() {                            @OverrIDe                            public voID run() {                                Map<String, Object> resultMap2 = new HashMap<>();                                resultMap2.put("message", "androID 主动调用 Flutter test 方法 delay 2000ms");                                resultMap2.put("code", 302);                                mMethodChannel.invokeMethod("test2", resultMap2);                            }                        }, 2000);                    } else if (lMethod.equals("test3")) {                        //测试通过Flutter打开AndroID Activity                        Toast.makeText(mContext, "Flutter 调用到了 androID test3", Toast.LENGTH_SHORT).show();                        Intent lintent = new Intent(MainActivity.this, TestMethodChannelActivity.class);                        MainActivity.this.startActivity(lintent);                    } else {                        result.notImplemented();                    }                }            }    );}

通过 Flutter_and_native_101 唯一标识将Flutter和andorID之间的 channel 连接起来。Flutter 传递对应的方法名称在native 接受方法后解析名称,在对比调用不同逻辑。

2、EventChannel:相当于接收来自native的通知

只能是原生发送消息给Flutter端,例如监听手机电量变化,网络变化,传感器等。

Flutter 端:

//EventChannel( 用于数据流(event streams)的通信)static const EventChannel _eventChannel = const EventChannel('Flutter_and_native_102');Future<dynamic> nativeMessageListener() async {  _eventChannel.receivebroadcastStream().Listen((arguments) {    int code = arguments["code"];    String message = arguments["message"];    setState(() {      recive +=          " code $code message $message \n";      print(recive);    });  }, one rror: (event) {    print(event);  });}

androID原生:

/** * 此方法适用于androID 系统有通知通知到Flutter的场景 * * */private voID eventChannelFunction() {    EventChannel lEventChannel = new EventChannel(getFlutterVIEw(), "Flutter_and_native_102");    lEventChannel.setStreamHandler(            new EventChannel.StreamHandler() {                @OverrIDe                public voID onListen(Object o, EventChannel.EventSink eventSink) {                    mEventSink = eventSink;                    Log.d("zxzx","event sink = " + o);                    mHandler.post(new Runnable() {                        @OverrIDe                        public voID run() {                            Map<String, Object> resultMap = new HashMap<>();                            resultMap.put("message", "注册成功");                            resultMap.put("code", 400);                            eventSink.success(resultMap);                        }                    });                }                @OverrIDe                public voID onCancel(Object o) {                }            }    );}

同理,Flutter注册监听,监听 Flutter_and_native_102 channel来的广播。

3、BasicmessageChannel :

它是可以双端通信的,Flutter端可以给AndroID发送消息,AndroID也可以给Flutter发送消息。

Flutter 端:

static const messageChannel = const BasicmessageChannel( 'Flutter_and_native_100', StandardMessageCodec());  //发送消息  Future<Map> sendMessage(Map Json) async {    Map reply = await messageChannel.send(Json);    //解析 原生发给 Flutter 的参数    int code = reply["code"];    String message = reply["message"];    setState(() {      recive = "code:$code message:$message";    });    return reply;  }  //接收消息监听  voID receiveMessage() {    messageChannel.setMessageHandler((result) async {      //解析 原生发给 Flutter 的参数      int code = result["code"];      String message = result["message"];      setState(() {        recive = "receiveMessage: code:$code message:$message";      });      return 'Flutter 已收到消息';    });  }

androID端:

private voID messageChannelFunction() {        //消息接收监听        //BasicmessageChannel (主要是传递字符串和一些半结构体的数据)        mMessageChannel = new BasicmessageChannel<Object>(getFlutterVIEw(), "Flutter_and_native_100", StandardMessageCodec.INSTANCE);        // 接收消息监听        mMessageChannel.setMessageHandler(new BasicmessageChannel.MessageHandler<Object>() {            @OverrIDe            public voID onMessage(Object o, BasicmessageChannel.Reply<Object> reply) {                System.out.println("onMessage: " + o.toString());                Map lJsONObject = null;                //解析Flutter 传递的参数                lJsONObject = (HashMap) o;                //方法名标识                Object lMethod = lJsONObject.get("method");                Log.d("MainActivity","lmethod = " + lMethod);                //测试 reply.reply()方法 发消息给Flutter                if (lMethod.equals("test")) {                    Toast.makeText(mContext, "Flutter 调用到了 androID test", Toast.LENGTH_SHORT).show();                    Map<String, Object> resultMap = new HashMap<>();                    resultMap.put("message", "reply.reply 返回给Flutter的数据");                    resultMap.put("code", 200);                    reply.reply(resultMap);                } else if (lMethod.equals("test2")) {                    //测试 mMessageChannel.send 发消息给Flutter                    channelSendMessage();                } else if (lMethod.equals("test3")) {                    //测试通过Flutter打开AndroID Activity                    Toast.makeText(mContext, "Flutter 调用到了 androID test3", Toast.LENGTH_SHORT).show();                    Intent lintent = new Intent(MainActivity.this, TestBasicmessageActivity.class);                    MainActivity.this.startActivity(lintent);                }            }        });    }    private voID channelSendMessage() {        Toast.makeText(mContext, "Flutter 调用到了 androID test", Toast.LENGTH_SHORT).show();        Map<String, Object> resultMap = new HashMap<>();        resultMap.put("message", "message Channel.reply 返回给Flutter的数据");        resultMap.put("code", 201);        mMessageChannel.send(resultMap, new BasicmessageChannel.Reply<Object>() {            @OverrIDe            public voID reply(Object o) {                Log.d("MainActivity", "mMessageChannel send 回调 " + o);            }        });    }

具体的使用哪种通信方式,看具体的使用场景。

 

 

总结

以上是内存溢出为你收集整理的Flutter与android原生通信全部内容,希望文章能够帮你解决Flutter与android原生通信所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1052585.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存