Flutter定义了三种不同类型的通信 Channel

BasicMessageChannel:用于传递字符串和半结构化的信息,持续通信,收到消息后可以回复此次消息,如:Native将遍历到的文件信息陆续传递到Dart,在比如:Flutter将从服务端陆陆续获取到信息交个Native加工,Native处理完返回等;

MethodChannel:用于传递方法调用(method invocation)一次性通信:如Flutter调用Native拍照;

EventChannel: 用于数据流(event streams)的通信,持续通信,收到消息后无法回复此次消息,通常用于Native向Dart的通信,如:手机电量变化,网络连接变化,陀螺仪,传感器等;

这三种类型的类型的Channel都是全双工通信,即A <=> B,Dart可以主动发送消息给platform端,并且platform接收到消息后可以做出回应,同样,platform端可以主动发送消息给Dart端,dart端接收数后返回给platform端。

注册如下
package flutterplatformchannelplugin.flutter_platform_channelplugin

import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.*
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

public class FlutterPlatformChannelpluginPlugin : FlutterPlugin, MethodCallHandler {
    private lateinit var methodChannel: MethodChannel
    private lateinit var basicMessageChannel: BasicMessageChannel

    //-----------------------------String name 三个注册的name不能一样 否则会报注册失败---------------///
    //以流的形式发送数据
    private lateinit var eventChannel: EventChannel
    private var eventSink: EventChannel.EventSink? = null
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        //basicMessageChannel 注册
        basicMessageChannel = BasicMessageChannel(flutterPluginBinding.flutterEngine.dartExecutor,
                "flutter_platform_channelplugin1", StandardMessageCodec.INSTANCE).apply {
            setMessageHandler(object : BasicMessageChannel.MessageHandler {
                override fun onMessage(p0: Any?, p1: BasicMessageChannel.Reply) {
                    println("-------dart 向这里传送的数据为sendData-------" + p0.toString())
                }
            })
        }
        //eventChannel 注册
        eventChannel = EventChannel(flutterPluginBinding.flutterEngine.dartExecutor,
                "flutter_platform_channelplugin2").apply {
            setStreamHandler(object : EventChannel.StreamHandler {
                override fun onListen(p0: Any?, p1: EventChannel.EventSink?) {
                    eventSink = p1!!
                }

                override fun onCancel(p0: Any?) {
                    eventSink = null
                }
            })
        }
        //methodChannel 注册
        methodChannel = MethodChannel(flutterPluginBinding.flutterEngine.dartExecutor, "flutter_platform_channelplugin").apply {
            setMethodCallHandler(this@FlutterPlatformChannelpluginPlugin)
        }

    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel.setMethodCallHandler(null)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == "testMethodChannel1") {
            Log.d("xg", "testMethodChannel1无参无返回值通信成功")
        } else if (call.method == "testMethodChannel2") {
            val params = call.arguments>()
            Log.d("xg", "testMethodChannel2有参无返回值" + params["data1"].toString())
        } else if (call.method == "testMethodChannel3") {
            val params = call.arguments()
            Log.d("xg", "testMethodChannel3有参有返回值" + params.toString())
            result.success("native接受到数据了")
        } else if (call.method == "doSendData") {
            sendData()
        } else if (call.method == "doEventSendData") {
            eventSink?.success("流数据来了11111111111111111111")
        } else {
            result.notImplemented()
        }
    }

    private fun sendData() {
        basicMessageChannel.send("BasicMessageChannel 进行原生向flutter主动通信发送数据", object : BasicMessageChannel.Reply {
            override fun reply(reply: Any?) {
                //可以通过下面方法读取保存在ThreadLocal变量中的值
                println("-------sendData-------" + reply.toString())
            }
        })
    }
}
  • BinaryMessenger messenger - 消息信使,是消息的发送与接收的工具;
  • String name - Channel的名字,也是其唯一标识符;假如项目用到多个通信工具,每个要保持不一样
  • MessageCodec codec - 消息的编解码器,它有几种不同类型的实现:
  • BinaryCodec - 最为简单的一种Codec,因为其返回值类型和入参的类型相同,均为二进制格式(Android中为ByteBuffer,iOS中为NSData)。实际上,BinaryCodec在编解码过程中什么都没做,只是原封不动将二进制数据消息返回而已。或许你会因此觉得BinaryCodec没有意义,但是在某些情况下它非常有用,比如使用BinaryCodec可以使传递内存数据块时在编解码阶段免于内存拷贝;
  • StringCodec - 用于字符串与二进制数据之间的编解码,其编码格式为UTF-8;
  • JSONMessageCodec - 用于基础数据与二进制数据之间的编解码,其支持基础数据类型以及列表、字典。其在iOS端使用了NSJSONSerialization作为序列化的工具,而在Android端则使用了其自定义的JSONUtil与StringCodec作为序列化工具;
  • StandardMessageCodec - 是BasicMessageChannel的默认编解码器,其支持基础数据类型、二进制数据、列表、字典,其工作原理

发送消息 ------原生向dart dart向原生都行

void send(T message)
void send(T message, BasicMessageChannel.Reply callback)

  • T message - 要传递给Dart的具体信息;
  • BasicMessageChannel.Reply callback - 消息发出去后,收到Dart或者原生的的回复的回调函数;

接受消息  原生向dart dart向原生都行

basicMessageChannel = BasicMessageChannel(flutterPluginBinding.flutterEngine.dartExecutor,
        "flutter_platform_channelplugin1", StandardMessageCodec.INSTANCE).apply {
    setMessageHandler(object : BasicMessageChannel.MessageHandler {
        override fun onMessage(p0: Any?, reply: BasicMessageChannel.Reply) 
            reply.reply("我是接受到dart的传送的数据原生给平台的反馈")
        }
    })
}

你可能感兴趣的:(flutter使用记录)