【Flutter 混合开发】与原生通信-BasicMessageChannel

Flutter 混合开发系列 包含如下:

  • 嵌入原生View-Android
  • 嵌入原生View-iOS
  • 与原生通信-MethodChannel
  • 与原生通信-BasicMessageChannel
  • 与原生通信-EventChannel
  • 添加 Flutter 到 Android Activity
  • 添加 Flutter 到 Android Fragment
  • 添加 Flutter 到 iOS

每个工作日分享一篇,欢迎关注、点赞及转发。

平台通信的3中方式

Flutter 与 Native 端通信有如下3个方法:

  • MethodChannel:Flutter 与 Native 端相互调用,调用后可以返回结果,可以 Native 端主动调用,也可以Flutter主动调用,属于双向通信。此方式为最常用的方式, Native 端调用需要在主线程中执行。
  • BasicMessageChannel:用于使用指定的编解码器对消息进行编码和解码,属于双向通信,可以 Native 端主动调用,也可以Flutter主动调用。
  • EventChannel:用于数据流(event streams)的通信, Native 端主动发送数据给 Flutter,通常用于状态的监听,比如网络变化、传感器数据等。

Flutter 端

Flutter 端创建 MethodChannel 通道,用于与原生端通信:

var channel = BasicMessageChannel('com.flutter.guide.BasicMessageChannel',StandardMessageCodec());

com.flutter.guide.BasicMessageChannel 是 BasicMessageChannel 的名称,原生端要与之对应。

发送消息:

var result = await channel.send({'name': 'laomeng', 'age': 18});
  • 参数类型任意,多个参数通常使用Map
  • 返回 Future,原生端返回的数据。

完整代码:

class BasicMessageChannelDemo extends StatefulWidget {
  @override
  _BasicMessageChannelDemoState createState() => _BasicMessageChannelDemoState();
}

class _BasicMessageChannelDemoState extends State<BasicMessageChannelDemo> {
  var channel = BasicMessageChannel('com.flutter.guide.BasicMessageChannel',StandardMessageCodec());

  var _data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          SizedBox(
            height: 50,
          ),
          RaisedButton(
            child: Text('发送数据到原生'),
            onPressed: () async {
              var result = await channel.send({'name': 'laomeng', 'age': 18});
              var name = result['name'];
              var age = result['age'];
              setState(() {
                _data = '$name,$age';
              });
            },
          ),
          Text('原生返回数据:$_data'),
        ],
      ),
    );
  }
}

Android 端

android 下创建 BasicMessageChannelDemo

class BasicMessageChannelDemo(messenger: BinaryMessenger) : BasicMessageChannel.MessageHandler<Any> {

    private var channel: BasicMessageChannel<Any>

    init {
        channel = BasicMessageChannel(messenger, "com.flutter.guide.BasicMessageChannel", StandardMessageCodec())
        channel.setMessageHandler(this)
    }

    override fun onMessage(message: Any?, reply: BasicMessageChannel.Reply<Any>) {
        val name = (message as Map<String, Any>)["name"]
        val age = (message as Map<String, Any>)["age"]

        var map = mapOf("name" to "hello,$name",
                "age" to "$age"
        )

        reply.reply(map)
    }
}

onMessage 方法在 Flutter 端调用 send 方法后调用,解析方法如下:

override fun onMessage(message: Any?, reply: BasicMessageChannel.Reply<Any>) {
        val name = (message as Map<String, Any>)["name"]
        val age = (message as Map<String, Any>)["age"]

        var map = mapOf("name" to "hello,$name",
                "age" to "$age"
        )

        reply.reply(map)
    }
  • message 是传入的参数,由于 Flutter 端传入的是 Map,所以上面的解析按照 Map 解析。
  • reply.reply() 是返回给 Flutter 的结果。

Flutter 端解析:

var result = await channel.send({'name': 'laomeng', 'age': 18});
var name = result['name'];
var age = result['age'];
两端的解析要相互对应。

MainActivity 启动:

class MainActivity : FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        BasicMessageChannelDemo(flutterEngine.dartExecutor.binaryMessenger)
        flutterEngine.plugins.add(MyPlugin())
    }
}

iOS 端

ios 下创建 MethodChannelDemo,按如下方式:

import Flutter
import UIKit

public class BasicMessageChannelDemo {
    
    var channel:FlutterBasicMessageChannel
    
    init(messenger: FlutterBinaryMessenger) {
        channel = FlutterBasicMessageChannel(name: "com.flutter.guide.BasicMessageChannel", binaryMessenger: messenger)
        channel.setMessageHandler { (message, reply) in
            if let dict = message as? Dictionary<String, Any> {
                let name:String = dict["name"] as? String ?? ""
                let age:Int = dict["age"] as? Int ?? -1
                reply(["name":"hello,\(name)","age":age])
            }
        }  
    }  
}

AppDelegate 启动:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    MethodChannelDemo(messenger: controller.binaryMessenger)
    BasicMessageChannelDemo(messenger: controller.binaryMessenger)
    GeneratedPluginRegistrant.register(with: self)

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

原生端主动发送消息给Flutter

Flutter 端接收数据
@override
  void initState() {
    super.initState();
    channel.setMessageHandler((message) {
      setState(() {
        _nativeData = message['count'];
      });
    });
  }
Android 发送数据

原生端启动定时器,每隔一秒向 Flutter 发送数据,Android 端代码:

class BasicMessageChannelDemo(var activity: Activity, messenger: BinaryMessenger) : BasicMessageChannel.MessageHandler<Any> {

    private var channel: BasicMessageChannel<Any>
    private var count = 0

    init {
        channel = BasicMessageChannel(messenger, "com.flutter.guide.BasicMessageChannel", StandardMessageCodec())
        channel.setMessageHandler(this)
        startTimer()
    }


    fun startTimer() {
        var timer = Timer().schedule(timerTask {
            activity.runOnUiThread {
                var map = mapOf("count" to count++)
                channel.send(map,object :BasicMessageChannel.Reply<Any>{
                    override fun reply(reply: Any?) {

                    }
                })
            }
        }, 0, 1000)

    }

    override fun onMessage(message: Any?, reply: BasicMessageChannel.Reply<Any>) {
        val name = (message as Map<String, Any>)["name"]
        val age = (message as Map<String, Any>)["age"]

        var map = mapOf("name" to "hello,$name",
                "age" to "$age"
        )

        reply.reply(map)
    }
}

注意:Android 端发送数据要在主现场中调用,即:

activity.runOnUiThread {
          var map = mapOf("count" to count++)
          channel.invokeMethod("timer", map)
      }

启动修改如下:

class MainActivity : FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        BasicMessageChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger)
        flutterEngine.plugins.add(MyPlugin())
    }
}

iOS 发送数据

iOS 端启动定时器代码如下:


import Flutter
import UIKit

public class BasicMessageChannelDemo {
    
    var channel:FlutterBasicMessageChannel
    var count =  0
    
    init(messenger: FlutterBinaryMessenger) {
        channel = FlutterBasicMessageChannel(name: "com.flutter.guide.BasicMessageChannel", binaryMessenger: messenger)
        channel.setMessageHandler { (message, reply) in
            if let dict = message as? Dictionary<String, Any> {
                let name:String = dict["name"] as? String ?? ""
                let age:Int = dict["age"] as? Int ?? -1
                reply(["name":"hello,\(name)","age":age])
            }
        }
        startTimer()
    }
    
    func startTimer() {
        var timer = Timer.scheduledTimer(timeInterval:1, target: self, selector:#selector(self.tickDown),userInfo:nil,repeats: true)
    }
    @objc func tickDown(){
        count += 1
        var args = ["count":count]
        channel.sendMessage(args) { (reply) in
            
        }
    }
}

交流

老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com

欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:

212 声望
35 粉丝
0 条评论
推荐阅读
Flutter 中不得不会的 mixin
mixin 是 Dart 中非常重要的概念,对于未接触过此概念的Coder来说尤其重要,最近看源码的时候,由于对 mixin 不熟悉导致理解出现偏差,走了很多弯路,所以这篇文章介绍一下 mixin 概念。

老孟1阅读 5.1k

一个 JSer 的 Dart 学习日志(四):异步编程
本文是“一个 JSer 的 Dart 学习日志”系列的第四篇,本系列文章主要以挖掘 JS 与 Dart 异同点的方式,在复习和巩固 JS 的同时平稳地过渡到 Dart 语言。鉴于作者尚属 Dart 初学者,所以认识可能会比较肤浅和片面,...

知名喷子阅读 1.5k

封面图
Android 开发中的SSL pinning
在日常的安全渗透过程中,我们经常会遇到瓶颈无处下手,这时候如果攻击者从APP进行突破,往往会有很多惊喜。但是目前市场上的APP都会为防止别人恶意盗取和恶意篡改进行一些保护措施,比如模拟器检测、root检测、A...

xiangzhihong阅读 1k

Flutter 这一年:2022 亮点时刻
2022 年,我们非常兴奋的看到 Flutter 社区持续发展壮大,也因此让更多人体验到了令人难以置信的体验。每天有超过 1000 款使用 Flutter 的新移动应用发布到 App Store 和 Google Play,Web 平台和桌面应用程序数...

Flutter阅读 833

flutter系列之:在flutter中使用流式布局
我们在开发web应用的时候,有时候为了适应浏览器大小的调整,需要动态对页面的组件进行位置的调整。这时候就会用到flow layout,也就是流式布局。

flydean阅读 805

Flutter for Web 首次首屏优化——JS 分片优化
Flutter for Web(FFW)从 2021 年发布至今,在国内外互联网公司已经得到较多的应用。作为 Flutter 技术在 Web 领域的有力扩充,FFW 可以让熟悉 Flutter 的客户端同学直接上手写 H5,复用 App 端代码高效支撑业务...

阿里巴巴终端技术阅读 777

封面图
个推支持小程序消息推送,助力开发者实现用户高触达、高转化
随着小程序技术和应用场景的不断完善,越来越多的开发者搭建了小程序平台,为用户带来更“轻量”的服务。在小程序用户迅猛增长的同时,开发者对于小程序用户精细化触达的需求也愈加强烈。近日,个推消息推送上线了...

个推阅读 695

封面图
212 声望
35 粉丝
宣传栏