文章目录

  • 前言
  • 一、Android 端 MethodChannel 构造函数
  • 二、Android 端 setMethodCallHandler 方法
  • 三、Android 端实现 MethodChannel 通信步骤
  • 四、相关资源

前言

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

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

一、Android 端 MethodChannel 构造函数


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

public class MethodChannel {private static final String TAG = "MethodChannel#";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 MethodChannel(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 MethodChannel(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 : 方法编解码器 ;

二、Android 端 setMethodCallHandler 方法


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

调用 setMethodCallHandler 方法 , 可以为 MethodChannel 设置一个 方法回调处理器 ;

MethodChannel.setMethodCallHandler 函数原型如下 :

  /*** Registers a method call 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 method call on this channel will be handled* silently by sending a null reply. This results in a <a* href="https://api.flutter.dev/flutter/services/MissingPluginException-class.html">MissingPluginException</a>* on the Dart side, unless an <a* href="https://api.flutter.dev/flutter/services/OptionalMethodChannel-class.html">OptionalMethodChannel</a>* is used.** @param handler a {@link MethodCallHandler}, or null to deregister.*/@UiThreadpublic void setMethodCallHandler(final @Nullable MethodCallHandler handler) {messenger.setMessageHandler(name, handler == null ? null : new IncomingMethodCallHandler(handler));}

设置的 final @Nullable MethodCallHandler handler 参数 , 就是 方法回调处理器 ;

在 MethodCallHandler 接口中 , 只有一个 onMethodCall 方法 , 该方法是用于接收 Dart 传递来的消息的 ;

void onMethodCall(@NonNull MethodCall call, @NonNull Result result);

onMethodCall 参数简介 :

  • MethodCall call : Dart 端传递来的消息 ;
  • Result result : 向 Dart 端回传的数据 ;

MessageHandler 接口原型如下 :

  /** A handler of incoming method calls. */public interface MethodCallHandler {/*** Handles the specified method call received from Flutter.** <p>Handler implementations must submit a result for all incoming calls, by making a single* call on the given {@link Result} callback. Failure to do so will result in lingering Flutter* result handlers. The result may be submitted asynchronously. Calls to unknown or* unimplemented methods should be handled using {@link Result#notImplemented()}.** <p>Any uncaught exception thrown by this method will be caught by the channel implementation* and logged, and an error result will be sent back to Flutter.** <p>The handler is called on the platform thread (Android main thread). For more details see* <a href="https://github.com/flutter/engine/wiki/Threading-in-the-Flutter-Engine">Threading in* the Flutter Engine</a>.** @param call A {@link MethodCall}.* @param result A {@link Result} used for submitting the result of the call.*/@UiThreadvoid onMethodCall(@NonNull MethodCall call, @NonNull Result result);}

在 MethodCall 中 , 主要有两个成员变量 :

  • String method : 表示调用的方法名 ;
  • Object arguments : 表示调用的参数 ;
/** Command object representing a method call on a {@link MethodChannel}. */
public final class MethodCall {/** The name of the called method. */public final String method;/*** Arguments for the call.** <p>Consider using {@link #arguments()} for cases where a particular run-time type is expected.* Consider using {@link #argument(String)} when that run-time type is {@link Map} or {@link* JSONObject}.*/public final Object arguments;
}

Result 接口中提供了 333 个方法 , 根据不同的结果 , 回调不同的接口方法 ;

  • void success(@Nullable Object result) : 表示调用成功 ;
  • error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) : 表示出现错误 ;
  • void notImplemented() : 表示要调用的函数在 Dart 端没有实现 ;
  /*** Method call result callback. Supports dual use: Implementations of methods to be invoked by* Flutter act as clients of this interface for sending results back to Flutter. Invokers of* Flutter methods provide implementations of this interface for handling results received from* Flutter.** <p>All methods of this class must be called on the platform thread (Android main thread). For* more details see <a* href="https://github.com/flutter/engine/wiki/Threading-in-the-Flutter-Engine">Threading in the* Flutter Engine</a>.*/public interface Result {/*** Handles a successful result.** @param result The result, possibly null. The result must be an Object type supported by the*     codec. For instance, if you are using {@link StandardMessageCodec} (default), please see*     its documentation on what types are supported.*/@UiThreadvoid success(@Nullable Object result);/*** Handles an error result.** @param errorCode An error code String.* @param errorMessage A human-readable error message String, possibly null.* @param errorDetails Error details, possibly null. The details must be an Object type*     supported by the codec. For instance, if you are using {@link StandardMessageCodec}*     (default), please see its documentation on what types are supported.*/@UiThreadvoid error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails);/** Handles a call to an unimplemented method. */@UiThreadvoid notImplemented();}

三、Android 端实现 MethodChannel 通信步骤


Android 端实现 MethodChannel 通信步骤 :

首先 , 初始化 MethodChannel 实例对象 ;

MethodChannel mMethodChannel = new MethodChannel(mFlutterFragment.getFlutterEngine().getDartExecutor(), "MethodChannel");

然后 , 为 MethodChannel 实例对象 设置 MethodChannel.MethodCallHandler , 用于接收 Flutter 端调用 Android 端方法 ;

mMethodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {@Overridepublic void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {show_message.setText("Dart 端通过 MethodChannel 调用 Android 端的 " + call.method + " 方法 , 参数是 " + call.arguments);}
});

最后 , 调用 mMethodChannel 的 invokeMethod 方法 , 调用 Flutter 中的方法 ;

findViewById(R.id.channel3).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mMethodChannel.invokeMethod("method", "arguments");}
});

四、相关资源


参考资料 :

  • 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 端实现 MethodChannel 通信 )相关推荐

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

    文章目录 前言 一.Android 端 EventChannel 构造函数 二.Android 端 setStreamHandler 方法 三.Android 端实现 EventChannel 通信步 ...

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

    文章目录 前言 一.Android 端 BasicMessageChannel 构造函数 二.Android 端 MessageCodec 子类实现 三.Android 端 setMessageHan ...

  3. 【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 完整代码示例 )

    文章目录 前言 一.Android 端完整代码示例 二.Flutter 端完整代码示例 三.相关资源 前言 前置博客 : [Flutter]Flutter 混合开发 ( Flutter 与 Nativ ...

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

    文章目录 一.EventChannel 简介 二.EventChannel 在 Dart 端的实现 1.EventChannel 构造方法 2.创建广播流 Stream 3.设置监听回调函数 4.Ev ...

  5. 【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 MethodChannel 通信 )

    文章目录 一.MethodChannel 简介 二.MethodChannel 在 Dart 端的实现 1.MethodChannel 构造函数 2.invokeMethod 函数 3.MethodC ...

  6. 【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 BasicMessageChannel 通信 )

    文章目录 一.BasicMessageChannel 简介 二.BasicMessageChannel 在 Dart 端的实现 1.BasicMessageChannel 构造方法 2.使用 Basi ...

  7. 【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 通信场景 | Channel 通信机制 | Channel 支持的通信数据类型 | Channel 类型 )

    文章目录 一.Flutter 和 Native 应用之间的通信场景 二.Flutter 和 Native 的 Channel 通信机制 三.Channel 通信机制支持的数据类型 四.Channel ...

  8. 干货 | 携程APP Native/RN内嵌Flutter UI混合开发实践和探索

    作者简介 Deway,携程资深工程师,iOS客户端开发,热衷于大前端和动态化技术: Frank,携程高级工程师,关注移动端热门技术,安卓客户端开发. 前言 随着各种多端技术的蓬勃发展,如今的移动端和前 ...

  9. 如何用 Flutter 实现混合开发?闲鱼公开源代码实例

    2019独角兽企业重金招聘Python工程师标准>>> 具有一定规模的 App 通常有一套成熟通用的基础库,尤其是阿里系 App,一般需要依赖很多体系内的基础库.那么使用 Flutt ...

最新文章

  1. TensorFlow2简单入门-三维张量
  2. ASN.1 Editor
  3. Linq之ToDictionaryTSource, TKey, TElement的写法
  4. Intel 64/x86_64/IA-32/x86处理器 - SIMD指令集 - MMX技术(2) - 数据转换指令
  5. 2018最新版硬盘装系统,不要U盘也能装
  6. Unity 和腾讯游戏成立联合创新实验室:从技术创新探索游戏产品新模式和概念
  7. DataTable.ImportRow()与DataTable.Rows.Add()的区别
  8. Mybatis 项目开发实际常用SQL笔记总结
  9. mac 装python环境下mysql_MAC OS X下安装MySQL-python
  10. 计算机四级网络工程师等级考试题库软件---百度云分享
  11. 新旧Oracle客户端连接远程oracle数据库
  12. matlab插值与拟合例题_数学建模matlab插值与拟合
  13. 网站流量模型(1)介绍
  14. c++语言如何判断奇偶数,C++ 判断奇数偶数
  15. Speech Representation预训练模型综述
  16. 从零开始学USB(一、基础知识1)
  17. Android开发效率提升利器-ButterKnife最全使用详解及ButterKnife插件的使用
  18. 开源中Web开发的各种资源
  19. WEBGUI中上一页(PgUp/Page Up)和下一页(PgDn/Page Down)键不起效
  20. 官宣!美国通讯芯片巨头博通610亿美元收购云计算巨头威睿 | 美通社头条

热门文章

  1. 为iframe添加鼠标事件
  2. Opencv中cvCopy() 和cvCloneImage()的区别
  3. [转载] 什么时候应该使用 ==?什么时候应该使用 Equals?
  4. 石川es6课程---3、变量let和常量const
  5. python+pywinauto之PC端自动化一
  6. BSGS扩展BSGS
  7. NPOI的excel导出1
  8. 【C/C++开发】C++实现简单的线程池
  9. nginx反向代理cas-server之2:生成证书,centOS下使用openssl生成CA证书(根证书、server证书、client证书)...
  10. ExtJs服务器端代理(Ajax)