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

移动开发 作者: 2024-08-25 08:30:01
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生

平台通信的3中方式

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

通信架构图

通信与平台线程

Handler(Looper.getMainLooper()).post {
  
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
  @Override
  public void run() {
    
  }
});
activity.runOnUiThread {
   
}
dispatch_async(dispatch_get_main_queue(),^{
  
});
DispatchQueue.main.async {
  
}

MethodChannel

Flutter 端

var channel = MethodChannel('com.flutter.guide.MethodChannel');
var result = await channel.invokeMethod('sendData',{'name': 'laomeng','age': 18})
  • 第一个参数表示method,方法名称,原生端会解析此参数。
  • 第二个参数表示参数,类型任意,多个参数通常使用Map
  • 返回 Future,原生端返回的数据。
class MethodChannelDemo extends StatefulWidget {
  @override
  _MethodChannelDemoState createState() => _MethodChannelDemoState();
}

class _MethodChannelDemoState extends State<MethodChannelDemo> {
  var channel = MethodChannel('com.flutter.guide.MethodChannel');

  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
                  .invokeMethod('sendData','age': 18});
              var name = result['name'];
              var age = result['age'];
              setState(() {
                _data = '$name,$age';
              });
            },Text('原生返回数据:$_data')
        ],);
  }
}

Android 端

package com.flutter.guide

import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

/**
 * des:
 */
class MethodChannelDemo(messenger: BinaryMessenger): MethodChannel.MethodCallHandler {

    private var channel: MethodChannel

    init {
        channel = MethodChannel(messenger,"com.flutter.guide.MethodChannel")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall,result: MethodChannel.Result) {
        
    }
}
override fun onMethodCall(call: MethodCall,result: MethodChannel.Result) {
    if (call.method == "sendData") {
        val name = call.argument("name") as String?
        val age = call.argument("age") as Int?

        var map = mapOf("name" to "hello,$name","age" to "$age"
        )
        result.success(map)
    }
}
  • call.method 字符串就是 invokeMethod 方法传入的 method
  • call.argument 是 invokeMethod 传入的参数,由于 Flutter 端传入的是 Map,所以上面的解析按照 Map 解析。
  • result.success() 是返回给 Flutter 的结果。
var result = await channel
    .invokeMethod('sendData','age': 18});
var name = result['name'];
var age = result['age'];
class MainActivity : FlutterActivity() {
    
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannelDemo(flutterEngine.dartExecutor.binaryMessenger)
    }
}

iOS 端

import Flutter
import UIKit

public class MethodChannelDemo {
    
    init(messenger: FlutterBinaryMessenger) {
        let channel = FlutterMethodChannel(name: "com.flutter.guide.MethodChannel",binaryMessenger: messenger)
        channel.setMethodCallHandler { (call:FlutterMethodCall,result:@escaping FlutterResult) in
            if (call.method == "sendData") {
                if let dict = call.arguments as? Dictionary<String,Any> {
                    let name:String = dict["name"] as? String ?? ""
                    let age:Int = dict["age"] as? Int ?? -1
                    result(["name":"hello,\(name)","age":age])
                }
            }
        }
    }
}

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)
    GeneratedPluginRegistrant.register(with: self)
    
    return super.application(application,didFinishLaunchingWithOptions: launchOptions)
  }
}

原生端主动发送消息给Flutter

Flutter 端接收数据
@override
void initState() {
  super.initState();
  channel.setMethodCallHandler((call) {
    setState(() {
      _nativeData = call.arguments['count'];
    });
  });
}
Android 发送数据
class MethodChannelDemo(var activity: Activity,messenger: BinaryMessenger) : MethodChannel.MethodCallHandler {

    private var channel: MethodChannel
    private var count = 0

    init {
        channel = MethodChannel(messenger,"com.flutter.guide.MethodChannel")
        channel.setMethodCallHandler(this)
        startTimer()
    }


    fun startTimer() {
        var timer = Timer().schedule(timerTask {
            activity.runOnUiThread {
                var map = mapOf("count" to count++)
                channel.invokeMethod("timer",map)
            }
        },1000)

    }

    override fun onMethodCall(call: MethodCall,result: MethodChannel.Result) {
        if (call.method == "sendData") {
            val name = call.argument("name") as String?
            val age = call.argument("age") as Int?

            var map = mapOf("name" to "hello,"age" to "$age"
            )
            result.success(map)
        }
    }
}
class MainActivity : FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger)
        flutterEngine.plugins.add(MyPlugin())
    }
}
iOS 发送数据
import Flutter
import UIKit

public class MethodChannelDemo {
    var count =  0
    var channel:FlutterMethodChannel
    init(messenger: FlutterBinaryMessenger) {
        channel = FlutterMethodChannel(name: "com.flutter.guide.MethodChannel","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.invokeMethod("timer",arguments:args)
    }
}

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68298.html