美文网首页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的使用

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