日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/6/17 62 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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 接收 333 個參數 :

  • 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.*/@UiThreadpublic 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 接口中 , 有 333 個方法 :

  • 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();}



三、Android 端實現 EventChannel 通信步驟



Android 端實現 EventChannel 通信步驟 :

首先 , 初始化 EventChannel 實例對象 ;

// 初始化 EventChannel 實例對象 EventChannel mEventChannel = new EventChannel(mFlutterFragment.getFlutterEngine().getDartExecutor(),"EventChannel");

然后 , 為 EventChannel 實例對象設置 EventChannel.StreamHandler ;

mEventChannel.setStreamHandler(new EventChannel.StreamHandler() {/*** 事件流建立成功會回調該方法* @param arguments* @param events*/@Overridepublic void onListen(Object arguments, EventChannel.EventSink events) {mEventSink = events;Log.i(TAG, "事件流建立成功");}@Overridepublic void onCancel(Object arguments) {mEventSink = null;} });

最后 , 調用 EventChannel.EventSink 的 success 方法 , 向 Flutter 端發送數據 ;

findViewById(R.id.channel2).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.i(TAG, "Native 通過 EventChannel 通道發送消息 , mEventSink : " + mEventSink);// 點擊按鈕 , 向 Flutter 端發送數據if (mEventSink != null) {mEventSink.success("Native 通過 EventChannel 通道發送消息 Hello !");}} });

注意 : 這里要特別注意 , Android 與 Flutter 中 EventChannel 的初始化流程 , 先初始化 Android 中的 EventChannel , 再初始化 Flutter 中的 EventChannel , 如果順序不對 , 無法進行通信 ;

【錯誤記錄】Flutter 混合開發報錯 ( Android 端與 Flutter 端 EventChannel 初始化順序錯誤導致無法通信 | EventChannel 通信流程 )





四、 Android 端與 Flutter 端 EventChannel 注冊與監聽流程



Android 端與 Flutter 端 EventChannel 注冊與監聽流程 :

① Android 端 初始化 EventChannel ;

// 初始化 EventChannel 實例對象 mEventChannel = new EventChannel(mFlutterFragment.getFlutterEngine().getDartExecutor(),"EventChannel");

② Android 端為 EventChannel 設置 EventChannel.StreamHandler ;

mEventChannel.setStreamHandler(new EventChannel.StreamHandler() {/*** 事件流建立成功會回調該方法* @param arguments* @param events*/@Overridepublic void onListen(Object arguments, EventChannel.EventSink events) {mEventSink = events;Log.i(TAG, "事件流建立成功");}@Overridepublic void onCancel(Object arguments) {mEventSink = null;} });

③ Flutter 端注冊監聽 ;

// 注冊 EventChannel 監聽 _streamSubscription = _eventChannel.receiveBroadcastStream() /// StreamSubscription<T> listen(void onData(T event)?, /// {Function? onError, void onDone()?, bool? cancelOnError});.listen(/// EventChannel 接收到 Native 信息后 , 回調的方法(message) {print("Flutter _eventChannel listen 回調");setState(() {/// 接收到消息 , 顯示在界面中showMessage = message;});},onError: (error){print("Flutter _eventChannel listen 出錯");print(error);} );

④ Android 端的 EventChannel.StreamHandler 接口的 onListen 回調 , 此時可以在 Android 端持有 EventChannel.EventSink events , 可以借助該對象向 Flutter 發送數據 ;

/*** 事件流建立成功會回調該方法* @param arguments* @param events*/ @Override public void onListen(Object arguments, EventChannel.EventSink events) {mEventSink = events;Log.i(TAG, "事件流建立成功"); }

⑥ Android 端調用 EventChannel.EventSink 發送數據 ;

// 點擊按鈕 , 向 Flutter 端發送數據 if (mEventSink != null) {mEventSink.success("Native 通過 EventChannel 通道發送消息 Hello !"); }

⑦ Flutter 端接收到 Android 端發送的數據 ; 回調 listen 方法的如下匿名方法參數 ;

(message) {print("Flutter _eventChannel listen 回調");setState(() {/// 接收到消息 , 顯示在界面中showMessage = message;});

上述流程 , 必須按照順序執行 , 否則注冊監聽失敗 ;





五、相關資源



參考資料 :

  • Flutter 官網 : https://flutter.dev/
  • Flutter 插件下載地址 : https://pub.dev/packages
  • Flutter 開發文檔 : https://flutter.cn/docs ( 強烈推薦 )
  • 官方 GitHub 地址 : https://github.com/flutter
  • Flutter 中文社區 : https://flutter.cn/
  • Flutter 實用教程 : https://flutter.cn/docs/cookbook
  • Flutter CodeLab : https://codelabs.flutter-io.cn/
  • Dart 中文文檔 : https://dart.cn/
  • Dart 開發者官網 : https://api.dart.dev/
  • Flutter 中文網 : https://flutterchina.club/ , http://flutter.axuer.com/docs/
  • Flutter 相關問題 : https://flutterchina.club/faq/ ( 入門階段推薦看一遍 )
  • GitHub 上的 Flutter 開源示例 : https://download.csdn.net/download/han1202012/15989510
  • Flutter 實戰電子書 : https://book.flutterchina.club/chapter1/
  • Dart 語言練習網站 : https://dartpad.dartlang.org/

重要的專題 :

  • Flutter 動畫參考文檔 : https://flutterchina.club/animations/

博客源碼下載 :

  • GitHub 地址 : ( 隨博客進度一直更新 , 有可能沒有本博客的源碼 )

    • Flutter Module 工程 : https://github.com/han1202012/flutter_module
    • Android 應用 : https://github.com/han1202012/flutter_native
    • 注意 : 上面兩個工程要放在同一個目錄中 , 否則編譯不通過 ;
  • 博客源碼快照 : https://download.csdn.net/download/han1202012/21670919 ( 本篇博客的源碼快照 , 可以找到本博客的源碼 )

總結

以上是生活随笔為你收集整理的【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | Android 端实现 EventChannel 通信 )的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。