笔记:
您可以通过实现 ActivityAware 接口来获取对活动的引用,但是如果您setMethodCallHandler(...)
在onAttachToEngine()
方法onAttachToActivity()
中将永远不会被调用并且您将永远无法访问活动
看看下面的例子
什么不工作:
在下面的例子onAttachToActivity()
中永远不会被调用
class AndroidLongTaskPlugin : FlutterPlugin, ActivityAware {
private var activity: FlutterActivity? = null
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
//activity is null here
//also onAttachToActivity will never be called because we are calling setMethodHandler here
channel = MethodChannel(binaryMessenger, CHANNEL_NAME)
channel.setMethodCallHandler { call, result ->
//our code
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel?.setMethodCallHandler(null)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity as FlutterActivity
}
//rest of the methods
}
这是一个工作示例:
class MyPlugin : FlutterPlugin, ActivityAware {
private var activity: FlutterActivity? = null
private var binaryMessenger: BinaryMessenger? = null
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
binaryMessenger = flutterPluginBinding.binaryMessenger
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
Log.d("DART/NATIVE", "onDetachedFromEngine")
channel?.setMethodCallHandler(null)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
Log.d("DART/NATIVE", "onAttachedToActivity")
activity = binding.activity as FlutterActivity
//here we have access to activity
//also make sure to setMethodCallHandler here
channel.setMethodCallHandler { call, result ->
//our code
}
}
//rest of the methods
}