[混編] iOS原生專案- iOS/flutter 程式碼互動

路過看風景發表於2021-03-29

平臺通訊的3中方式 Flutter 與 Native 端通訊有如下3個方法:

 MethodChannel:Flutter 與 Native 端相互呼叫,呼叫後可以返回結果,可以 Native 端主動呼叫,也可以Flutter主動呼叫,屬於雙向通訊。此方式為最常用的方式, Native 端呼叫需要在主執行緒中執行。

BasicMessageChannel:用於使用指定的編解碼器對訊息進行編碼和解碼,屬於雙向通訊,可以 Native 端主動呼叫,也可以Flutter主動呼叫。

EventChannel:用於資料流(event streams)的通訊, Native 端主動傳送資料給 Flutter,通常用於狀態的監聽,比如網路變化、感測器資料等。

Flutter 與 Native 端通訊是非同步的。

 通訊與平臺執行緒 Native 端主動傳送資料給 Flutter時,Native 端程式碼需要在主執行緒中執行,Android 端從子執行緒跳轉到主執行緒方式:
Kotlin 程式碼: Handler(Looper.getMainLooper()).post { } 
Java 程式碼:

new Handler(Looper.getMainLooper()).post(new Runnable() {
  @Override
  public void run() {

  }
});
複製程式碼

 如果可以獲取到當前 Activity,也可以使用如下方式:
activity.runOnUiThread { } 

iOS 端從子執行緒跳轉到主執行緒方式:
Objective-C 程式碼: dispatch_async(dispatch_get_main_queue(), ^{ }); 
Swift 程式碼: DispatchQueue.main.async { }

MethodChannel
Flutter 端 Flutter 端建立 MethodChannel 通道,用於與原生端通訊:

 var channel = MethodChannel('com.flutter.guide.MethodChannel');
com.flutter.guide.MethodChannel 是 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', {'name': 'laomeng', 'age': 18});
              var name = result['name'];
              var age = result['age'];
              setState(() {
                _data = '$name,$age';
              });
            },
          ),
          Text('原生返回資料:$_data')
        ],
      ),
    );
  }
} 
複製程式碼

Android 端 android 下建立 MethodChannelDemo:

 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) {

    }
}
複製程式碼

onMethodCall 方法在 Flutter 端呼叫 invokeMethod 方法回撥,
解析方法如下:

 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 的結果。
Flutter 端解析:
var result = await channel .invokeMethod('sendData', {'name': 'laomeng', 'age': 18});
var name = result['name']; var age = result['age']; 
兩端的解析要相互對應。
在 MainActivity 啟動:

 class MainActivity : FlutterActivity() {
 override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannelDemo(flutterEngine.dartExecutor.binaryMessenger)
    }
}
複製程式碼

iOS 端 ios 下建立 MethodChannelDemo,
按如下方式:

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])
                }
            }
        }
    }
}  
複製程式碼

在 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)
    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 傳送資料 原生端啟動定時器,每隔一秒向 Flutter 傳送資料,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)
            }
        }, 0, 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,$name",
                    "age" to "$age"
            )
            result.success(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)
        MethodChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger)
        flutterEngine.plugins.add(MyPlugin())
    }
} 
複製程式碼

iOS 傳送資料 iOS 端啟動定時器程式碼如下:

 import Flutter
import UIKit

public class MethodChannelDemo {
    var count =  0
    var channel:FlutterMethodChannel
    init(messenger: FlutterBinaryMessenger) {
        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])
                }
            }
        }
        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)
    }
}
複製程式碼

相關文章