Flutter 调用 Android Native 的方法,是通过MethodChannel的方式来实现的:
在Android端:
创建一个Class,实现FlutterPlugin和MethodCallHandler接口
重写onAttachedToEngine(),onDetachedFromEngine(),onMethodCall()
onAttachedToEngine()中,根据自定义的CHANNEL_NAME创建MethodChannel, onDetachedFromEngine中,释放MethodChannel
onMethodCall中,通过自定义的METHOD_NAME,来响应Flutter中,invokeMethod对Native的通信,代码如下
class MethodChannelPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
private var methodChannel: MethodChannel? = null
private var mNoteForFlutterListener: NoteForFlutterListener? = null
companion object {
private const val CHANNEL_NAME = "method_channel"
private const val METHOD_NAME = "saveNote"
val instance: MethodChannelPlugin by lazy(mode = LazyThreadSafetyMode.SYNCH