接著來看Native 端(Android):
預設建立的android/.../BatterylevelPlugin.kt
:
class BatterylevelPlugin: 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 lateinit var channel : MethodChannel
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "batterylevel")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
這邊用來實現Native 端(Android)的功能,首先會實作**FlutterPlugin
與MethodCallHandler
**接口
FlutterPlugin
接口,必須實作onAttachedToEngine
以及onDetachedFromEngine
方法
onAttachedToEngine
:插件被FlutterEngine
加載時調用,可以做一些初始化工作,預設已在這邊設置好MethodChannel
的通道名稱(需要與Flutter 端使用的MethodChannel
名稱相對應),並通過MethodChannel
呼叫setMethodCallHandler
來註冊一個MessageHandler
來接收此通道訊息,設定為this
是因為BatterylevelPlugin
已實作MethodCallHandler
接口,所以能夠處理接收通道的訊息onDetachedFromEngine
:插件從FlutterEngine
移除時調用,可以做一些清理工作,這邊對MethodChannel
呼叫setMethodCallHandler
設定為null
,將此通道進行註銷MethodCallHandler
接口,就必須實作onMethodCall
,目的可讓MethodChannel
調用setMethodCallHandler
,實現從Flutter 端要調用的原生方法,這邊對Flutter 端呼叫的方法getPlatformVersion
做功能的實現,當Flutter 端呼叫此方法,就會回傳現在Android 的版本資訊回去