Android开发

Flutter与Android通信的三种方式

2020-10-08  本文已影响0人  旺仔_100

一、 MethodChannel
主要是flutter端调用android方法。flutter调取android方法,也可以android主动跟flutter通信,但是这个只能是传递数据,不是调方法。MethodChannel的flutter调取android方法,我之前写过,可以查看如下链接,https://www.jianshu.com/p/6b677ff3350e

Android主动跟flutter通信,如下

static var platpform = const MethodChannel("com.flutter.guide.MyFlutterView");
 platpform.setMethodCallHandler((call) {
      nativeData = call.arguments["count"];
      setState(() {
      });

      print("count $nativeData");
    });
package com.example.flutter_demo

import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
import java.util.*
import kotlin.concurrent.timerTask

class  MethodChannelDemo(var activity: MainActivity,messenger: BinaryMessenger){
    private  var channel: MethodChannel
    private var count = 0
    init {
        channel = MethodChannel(messenger, "com.flutter.guide.MyFlutterView")
        Timer().schedule(timerTask {
            activity.runOnUiThread {
                var map = mapOf("count" to count++)
                channel.invokeMethod("timer", map)
            }
        },0,1000)

    }
}
MethodChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger)

二、 BasicMessageChannel
它是可以双端通信的,flutter端可以给Android发送消息,Android也可以给Flutter发送消息。

 static var basicChannel = const BasicMessageChannel("com.flutter.guide.MyFlutterView", StandardMessageCodec());
 result =  await basicChannel.send({'name':'azy','age' : 19});
 var basicMessageChannel = BasicMessageChannel(messager, "com.flutter.guide.MyFlutterView", StandardMessageCodec())
        basicMessageChannel.setMessageHandler { message, reply ->
            var map = message as Map<String, Any>
            text.text = "原生的textvieww : ${map["name"]}, ${map["age"]}"
            //被动回复 flutter 消息
          reply.reply("I get it")
            //主动给 flutter 发消息
            basicMessageChannel.send("我还可以主动告诉你,我是个男的")
        }
basicChannel.setMessageHandler((message) async {
     this.message = message;
   });

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

 EventChannel(messager,"com.flutter.guide.MyFlutterView").setStreamHandler(object : EventChannel.StreamHandler{
                override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                    for (i in 0 .. 10){
                        events?.success(i)
                    }
                    events?.endOfStream()
                }

                override fun onCancel(arguments: Any?) {

                }

            })
 static var eventChannel = const EventChannel("com.flutter.guide.MyFlutterView");
   eventChannel.receiveBroadcastStream().listen((event) {
      print("event "+event.toString());
    },onDone: (){
      print("done");
    },onError: (object){
      print("on error $object");
    });

打印结果如下:

2020-10-08 16:12:29.578 14515-14594/com.example.flutter_demo I/flutter: event 0
2020-10-08 16:12:29.578 14515-14594/com.example.flutter_demo I/flutter: event 1
2020-10-08 16:12:29.578 14515-14594/com.example.flutter_demo I/flutter: event 2
2020-10-08 16:12:29.578 14515-14594/com.example.flutter_demo I/flutter: event 3
2020-10-08 16:12:29.579 14515-14594/com.example.flutter_demo I/flutter: event 4
2020-10-08 16:12:29.579 14515-14594/com.example.flutter_demo I/flutter: event 5
2020-10-08 16:12:29.579 14515-14594/com.example.flutter_demo I/flutter: event 6
2020-10-08 16:12:29.579 14515-14594/com.example.flutter_demo I/flutter: event 7
2020-10-08 16:12:29.579 14515-14594/com.example.flutter_demo I/flutter: event 8
2020-10-08 16:12:29.579 14515-14594/com.example.flutter_demo I/flutter: event 9
2020-10-08 16:12:29.580 14515-14594/com.example.flutter_demo I/flutter: event 10
2020-10-08 16:12:29.570 14515-14515/com.example.flutter_demo W/1.raster: type=1400 audit(0.0:2234682): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=22601 scontext=u:r:untrusted_app:s0:c129,c256,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2020-10-08 16:12:29.580 14515-14595/com.example.flutter_demo E/libc: Access denied finding property "vendor.debug.egl.swapinterval"
2020-10-08 16:12:29.580 14515-14594/com.example.flutter_demo I/flutter: done

总结一下:
MethodChannel是flutter调取原生方法的,也可以原生主动传递数据给Flutter。
BasicMessageChannel是两个端相互发送数据,接收数据的。
EventChannel 是android频繁发送数据给Flutter端的。

tip:多种类型的通道混用可能会出现报错问题。

上一篇下一篇

猜你喜欢

热点阅读