【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | Android 端实现 EventChannel 通信 )(一)

文章目录

前言

一、Android 端 EventChannel 构造函数

二、Android 端 setStreamHandler 方法

三、Android 端实现 EventChannel 通信步骤

四、 Android 端与 Flutter 端 EventChannel 注册与监听流程


前言

本博客与 【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 EventChannel 通信 ) 博客相对应 , 该博客中开发 Flutter 的 Dart 端 ;


本博客中开发 Android 中的 Java 端 , 最终目标是二者可以进行信息交流 ;






一、Android 端 EventChannel 构造函数


Android 端 Java 中 , EventChannel 构造函数方法原型如下 :


public final class EventChannel {
  private static final String TAG = "EventChannel#";
  private final BinaryMessenger messenger;
  private final String name;
  private final MethodCodec codec;
  /**
   * Creates a new channel associated with the specified {@link BinaryMessenger} and with the
   * specified name and the standard {@link MethodCodec}.
   *
   * @param messenger a {@link BinaryMessenger}.
   * @param name a channel name String.
   */
  public EventChannel(BinaryMessenger messenger, String name) {
    this(messenger, name, StandardMethodCodec.INSTANCE);
  }
  /**
   * Creates a new channel associated with the specified {@link BinaryMessenger} and with the
   * specified name and {@link MethodCodec}.
   *
   * @param messenger a {@link BinaryMessenger}.
   * @param name a channel name String.
   * @param codec a {@link MessageCodec}.
   */
  public EventChannel(BinaryMessenger messenger, String name, MethodCodec codec) {
    if (BuildConfig.DEBUG) {
      if (messenger == null) {
        Log.e(TAG, "Parameter messenger must not be null.");
      }
      if (name == null) {
        Log.e(TAG, "Parameter name must not be null.");
      }
      if (codec == null) {
        Log.e(TAG, "Parameter codec must not be null.");
      }
    }
    this.messenger = messenger;
    this.name = name;
    this.codec = codec;
  }
}


BasicMessageChannel 接收 3 33 个参数 :


BinaryMessenger messenger : 用于 发送 / 接收消息 ;

String name : Channel 消息通道的名称 , 该名称必须与 Dart 中的消息通道名称相同 ;

MethodCodec codec : 方法编解码器 ;


如果使用 EventChannel(BinaryMessenger messenger, String name) 构造函数 , 不传入 MethodCodec , 那么会传入 标准的方法编解码器 StandardMethodCodec ;






二、Android 端 setStreamHandler 方法


创建了 EventChannel 实例对象后 , 如果要接收 Dart 端发送来的消息 , 需要设置 消息处理器 ;


调用 setStreamHandler 方法 , 可以为 EventChannel 设置一个 消息处理器 ;



EventChannel.setStreamHandler 函数原型如下 :


/**
   * Registers a stream handler on this channel.
   *
   * <p>Overrides any existing handler registration for (the name of) this channel.
   *
   * <p>If no handler has been registered, any incoming stream setup requests will be handled
   * silently by providing an empty stream.
   *
   * @param handler a {@link StreamHandler}, or null to deregister.
   */
  @UiThread
  public void setStreamHandler(final StreamHandler handler) {
    messenger.setMessageHandler(
        name, handler == null ? null : new IncomingStreamRequestHandler(handler));
  }


设置的 final @Nullable StreamHandler handler 参数 , 就是 消息处理器 ;


在 StreamHandler 接口中 , 定义了两个接口方法 : onListen 和 onCancel 方法 ;


void onListen(Object arguments, EventSink events) : 用于接收 Dart 端所发送的消息 ;


Object arguments 参数 : Dart 端发送的数据 ;

EventSink events 参数 : Android 中收到了 Dart 端数据 , 要回调 Dart 时回调的函数 ;


StreamHandler 接口原型如下 :


/**
   * Handler of stream setup and teardown requests.
   *
   * <p>Implementations must be prepared to accept sequences of alternating calls to {@link
   * #onListen(Object, EventSink)} and {@link #onCancel(Object)}. Implementations should ideally
   * consume no resources when the last such call is not {@code onListen}. In typical situations,
   * this means that the implementation should register itself with platform-specific event sources
   * {@code onListen} and deregister again {@code onCancel}.
   */
  public interface StreamHandler {
    /**
     * Handles a request to set up an event stream.
     *
     * <p>Any uncaught exception thrown by this method will be caught by the channel implementation
     * and logged. An error result message will be sent back to Flutter.
     *
     * @param arguments stream configuration arguments, possibly null.
     * @param events an {@link EventSink} for emitting events to the Flutter receiver.
     */
    void onListen(Object arguments, EventSink events);
    /**
     * Handles a request to tear down the most recently created event stream.
     *
     * <p>Any uncaught exception thrown by this method will be caught by the channel implementation
     * and logged. An error result message will be sent back to Flutter.
     *
     * <p>The channel implementation may call this method with null arguments to separate a pair of
     * two consecutive set up requests. Such request pairs may occur during Flutter hot restart. Any
     * uncaught exception thrown in this situation will be logged without notifying Flutter.
     *
     * @param arguments stream configuration arguments, possibly null.
     */
    void onCancel(Object arguments);
  }


EventSink 接口中 , 有 3 33 个方法 :


success : 表示接收数据成功 ;

error : 表示接收数据出现错误 ;

endOfStream : 表示接收数据结束 ;

 

/**
   * Event callback. Supports dual use: Producers of events to be sent to Flutter act as clients of
   * this interface for sending events. Consumers of events sent from Flutter implement this
   * interface for handling received events (the latter facility has not been implemented yet).
   */
  public interface EventSink {
    /**
     * Consumes a successful event.
     *
     * @param event the event, possibly null.
     */
    void success(Object event);
    /**
     * Consumes an error event.
     *
     * @param errorCode an error code String.
     * @param errorMessage a human-readable error message String, possibly null.
     * @param errorDetails error details, possibly null
     */
    void error(String errorCode, String errorMessage, Object errorDetails);
    /**
     * Consumes end of stream. Ensuing calls to {@link #success(Object)} or {@link #error(String,
     * String, Object)}, if any, are ignored.
     */
    void endOfStream();
  }



上一篇:dart系列之:集合使用最佳实践


下一篇:【错误记录】发布 Flutter 插件包报错 ( Failed to upload the package.pub finished with exit code 1 )