美文网首页Flutter飞起
flutter-channel的使用

flutter-channel的使用

作者: 浮华_du | 来源:发表于2021-07-15 17:00 被阅读0次

flutter与flutter plugin之间通过PlatformChannel进行通信,之前我们介绍过的flutter plugin都是使用了MethodChannel,除此之外,还有BasicMessageChannel和EventChannel.

  • BasicMessageChannel:用来传递字符串和半结构化信息(json)
  • MethodChannel: 用来传递方法调用
  • EventChannel:用于数据流通信 (native->flutter)

BasicMessageChannel的使用

flutter中调用

BasicMessageChannel _basicChannel =
                              BasicMessageChannel(
                                  "basic_channel", StandardMessageCodec());
                          String result = await _basicChannel.send({"a":1}) as String;
                          TKToast.show("返回来了--$result");

Android,在MainActivity中(kotlin)

class MainActivity: FlutterActivity() {
 override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
     var binary: BinaryMessenger? = getFlutterEngine()?.dartExecutor?.binaryMessenger;
     if (binary != null){
         var mMessageChannel = BasicMessageChannel(binary,"basic_channel",StandardMessageCodec.INSTANCE);
         mMessageChannel.setMessageHandler({ message,callback->String
             print(message)
             callback.reply("android返回")
         });
     }
 }
}

iOS,在AppDelegate中didFinishLaunchingWithOptions中直接调用下面方法(Swift)

private func basicMessageChannelFunction(){
        if let controller:FlutterViewController = self.window.rootViewController as? FlutterViewController{
            let basicChannel:FlutterBasicMessageChannel = FlutterBasicMessageChannel.init(name: "basic_channel", binaryMessenger: controller as! FlutterBinaryMessenger)
            basicChannel.setMessageHandler { idMessage, callback in
                print(idMessage)
                callback("iOS返回");
            }
        }
    }

EventChannel的使用

flutter中

                          EventChannel _eventChannel = const EventChannel('event_channel');
                         StreamSubscription _streamSubscription = _eventChannel.receiveBroadcastStream().listen((event) {
                            print(event);
                          });
//_streamSubscription.cancle()记得关闭哦~

Android的MainActivity中

class MainActivity: FlutterActivity() {

    var eventSink: EventChannel.EventSink? = null

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
     super.configureFlutterEngine(flutterEngine)
     var binary: BinaryMessenger? = getFlutterEngine()?.dartExecutor?.binaryMessenger;
     if (binary != null){
         var eventChannel = EventChannel(binary,"event_channel");
         eventChannel.setStreamHandler(object : EventChannel.StreamHandler {
             override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                 eventSink = events!!
                 Log.w("android","eventchannel-onlisten")
                 eventSink!!.success("success")
                 Thread {
                     try {
                         while (true) {//每隔1秒,发送一次
                             Thread.sleep(1000)
                             runOnUiThread {
                                 eventSink!!.success("android")
                             }
                         }
                     } catch (e: InterruptedException) {
                         e.printStackTrace()
                     }
                 }.start()
             }
             override fun onCancel(arguments: Any?) {
                Log.w("android","eventchannel--cancle")
             }
         })

     }
 }
}

iOS中

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate,FlutterStreamHandler {

 
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    eventChannelFunction()
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }


    private func eventChannelFunction(){
        if let controller:FlutterViewController = self.window.rootViewController as? FlutterViewController{
            let eventChannel:FlutterEventChannel = FlutterEventChannel.init(name: "event_channel", binaryMessenger: controller as! FlutterBinaryMessenger)
            eventChannel.setStreamHandler(self)//(FlutterStreamHandler & NSObjectProtocol)?
            
        }
    }
    
    var eventSink:FlutterEventSink?
    
    @objc func sendMessage(){
        if let sink = eventSink{
            sink("iOS")
        }
    }
    
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events;
        eventSink!("success")
        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(sendMessage), userInfo: nil, repeats: true)
//每隔1秒发一次
//eventSink?.endOfStream()
//eventSink?.error("error code", "error message","error details")
        return nil;
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        print("iOS---eventchannel--cancle")
        return nil;
    }
    
}

注意: EventChannel涉及数据流的传递,各种计时器及stream使用完毕请务必关闭

更多相关内容,可查阅 https://www.jianshu.com/p/39575a90e820

相关文章

  • flutter-channel的使用

    flutter与flutter plugin之间通过PlatformChannel进行通信,之前我们介绍过的flu...

  • Flutter-channel详解

    简介 ​ BinaryMessenger是Platform端与Flutter端通信的工具,其通信使用的消息格式...

  • iconfont的使用(下载使用)

    1、下载文件 2、在生命周期中引入项目 beforeCreate () { var domModule = ...

  • Gson的使用--使用注解

    Gson为了简化序列化和反序列化的过程,提供了很多注解,这些注解大致分为三类,我们一一的介绍一下。 自定义字段的名...

  • 记录使用iframe的使用

    默认记录一下----可以说 这是我第一次使用iframe 之前都没有使用过; 使用方式: 自己开发就用了这几个属...

  • with的使用

    下面例子可以具体说明with如何工作: 运行代码,输出如下

  • this的使用

    什么是this? this是一个关键字,这个关键字总是返回一个对象;简单说,就是返回属性或方法“当前”所在的对象。...

  • this的使用

    JS中this调用有几种情况 一:纯粹的函数调用 这是函数的最通常用法,属于全局性调用,因此this就代表全局对象...

  • ==的使用

    积累日常遇到的编码规范,良好的编码习惯,持续更新。。。 日常使用==用于判断的时候,习惯性将比较值写前面,变量写后...

  • this的使用

    1.默认绑定,就是函数立即执行。 函数立即执行就是指向window,但是如果是node环境,就是指向全局conso...

网友评论

    本文标题:flutter-channel的使用

    本文链接:https://www.haomeiwen.com/subject/bfappltx.html