在Flutter中调用Android的代码
在Flutter中调用Android原生代码通常涉及以下步骤:
- 创建一个继承自
MethodChannel.MethodCallHandler
的FlutterPlugin
类。 - 实现
onAttachedToEngine
和onDetachedFromEngine
方法,以管理插件的生命周期。 - 在
onAttachedToEngine
方法中,注册处理来自Flutter的方法调用的处理程序。 - 使用
MethodChannel
与Flutter端进行通信。 - 在Android的
MainActivity
类中,使用GeneratedPluginRegistrant.registerWith
来自动注册所有的插件。
以下是一个简单的例子:
Android端:
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry.Registrar;
public class MyPlugin implements FlutterPlugin, MethodChannel.MethodCallHandler {
private MethodChannel channel;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "my_plugin");
channel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "my_plugin");
channel.setMethodCallHandler(new MyPlugin());
}
}
iOS端(Swift):
import Flutter
import UIKit
public class SwiftMyPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "my_plugin", binaryMessenger: registrar.messenger())
let instance = SwiftMyPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "getPlatformVersion" {
result(UIDevice.current.systemVersion)
} else {
result(FlutterMethodNotImplemented)
}
}
}
在Flutter端调用:
import 'package:flutter/services.dart';
class MyPlugin {
static const MethodChannel _channel = Me
评论已关闭