Flutter与Android之间不为人知的通信秘密

174 阅读2分钟

三种通道

Android与Flutter之间进行通信主要是依赖是平台通道PlatformChannel; 通道主要有以下三种:

  • 基本信息通道(BasicMessageChannel): 用来传递字符串和半结构化信息; 双向传递
  • 方法通道(MethodChannel): 用来传递方法的调用(method invocation); 双向传递
  • 数据流通道(EventChannel): 用于数据流(event streams)之间的通信

planformChannel.png

通道重要成员变量

name

  • 类型: String
  • 含义: Channel名(唯一标识符)
  • 作用:
    • Channel之间使用name进行区分
    • 当有消息从Flutter传递到Platform端时,会根据其传递过来的channel name找到该Channel对应的消息处理器(Handler)

massager

  • 类型: BinaryMessenger
  • 含义: Platform端与Flutter端通信的工具(格式:二进制)
  • 作用:
    • Channel与BinaryMessageHandler一一对应
    • 当初始化Channel & 注册时,实际上会生成一个对应的BinaryMessHandler,并且以channel name为key,注册到Binarymessager中
    • 当flutter端发送消息到BinaryMessager时,BinaryMessager会根据其入参channel name找到对应的BinaryMessageHandler,并交予其处理

Codec

  • 类型: MessageCodec / MethodCodec
  • 含义: 消息的编解码器(将二进制格式的数据转化为Handle能够识别的数据)
  • 作用:
    • 解码: 由于Channel从BinaryMessageHandle接到收的消息是二进制格式的数据,无法直接使用.因此Channel会将该二进制的消息通过Codec解码为能够识别的信息传递给Handler处理
    • 编码: Handler处理完消息后,会通过回调函数返回result,并将result通过编码器编码为二进制格式数据,通过binaryMessage发送回flutter端

接收platform(android、ios)消息方式

  • BaiscMessageChannel: 使用的是setMessageHandler回调接收来自platform的信息
  • MethodChannel: 使用的是setMethodCallHandler回调接收来自platform的信息
  • EventChannel: 使用receiveBroadcastStream回调接收来自platform的消息

消息接收总结

  • 本质上 Platform Channel通信还是通过信使BinaryMessenger来完成消息的收、发操作。
  • 默认信使是ServicesBinding.instance!.defaultBinaryMessenger
  • codec先将消息message编码, binaryMessenger将编码后的消息发送给iOS、Android平台,并等待iOS、Android平台的回复消息。

点击跳转原文链接,如有侵权请联系删除