直接上干货
一.iOS
1.引入所需要的sdk(我们这里以数美sdk为例),使用swift编码,在桥接文件需要
#import "SmAntiFraud.h"
2.Runner目录下建立文件SwiftTestFlutterPlugin.swift ( 我们这里使用的channel name为 local_plugin)
import Foundation
public class SwiftTestFlutterPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "local_plugin", binaryMessenger: registrar.messenger())
let instance = SwiftTestFlutterPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
result(SmAntiFraud.shareInstance()?.getDeviceId() ?? "")
}
}
3.AppDelegate中引用SwiftTestFlutterPlugin
4.flutter项目中调用
MethodChannel _channel =
MethodChannel('local_plugin');
String shumeiID =
await _channel.invokeMethod("local_plugin");
print(shumeiID);
二.android
1.android-app-libs下引入所需要的sdk,并提供初始化及使用方法;这里我们使用kotlin
2.main-kotlin-com-example-包名文件夹下,建立插件 channel name 设置为:local_plugin
package com.example.android_app_flutter//(注意包名文件夹)
import android.os.Build
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
/** TestFlutterPlugin */
class TestFlutterPlugin : FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private var channel: MethodChannel? = null
override fun onAttachedToEngine(flutterPluginBinding: FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "local_plugin")
channel!!.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
val smDeviceId = SmManager.getInstance().getDeviceId()
result.success("Android $smDeviceId")
}
override fun onDetachedFromEngine(binding: FlutterPluginBinding) {
channel!!.setMethodCallHandler(null)
}
}
3.MainActivity中引入插件
package com.example.android_app_flutter
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.plugins.add(TestFlutterPlugin())
}
}
4.如果插件需要事先初始化,建立TestAppApplication,在oncreate中初始化.此文件也需要在AndroidManifest.xml中指定
package com.example.android_app_flutter
import android.app.Application
import io.flutter.app.FlutterApplication
class TestAppApplication : FlutterApplication() {
override fun onCreate() {
super.onCreate()
SmManager.getInstance().init(this)
}
}
5.flutter中使用方式同上
对您有帮助的话, 欢迎点点小心心~