一、获取上下文
刚开始写Flutter的时候,由于需要在Android端用到上下文,当时真是把我难住了,后来翻阅大佬们开源库的代码,发现一个办法:
class FlutterNativeHelperPlugin : FlutterPlugin, MethodCallHandler, ActivityAware
重点就是最后的
ActivityAware
我们实现这个接口后,会重写几个方法
private var mActivity: Activity? = null
//首次绑定到Activity
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
mActivity = binding.activity
}
//由于某些原因导致暂时解绑
override fun onDetachedFromActivityForConfigChanges() {
mActivity = null
}
//恢复绑定
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
mActivity = binding.activity
}
//解绑
override fun onDetachedFromActivity() {
mActivity = null
}
这样我们就可以拿到心心念念的 ‘上下文’ 了,然后继续开心的写代码…
二、监听生命周期
我们继续写着写着,由于业务需要,又发现了一个问题,我们需要在Android 端监听到 onResume、onPause,这又把我难住了,我又开始 ‘耐心’ 的翻阅源码,又发现了惊喜。我打开了 ActivityPluginBinding 这个类,发现里面竟然有它
通过注释我们可以得知,我们可以在flutter端引入flutter_plugin_android_lifecycle,来解决问题。
我们进入flutter_plugin_android_lifecycle,进行依赖。
在依赖完成之后,如果你是使用的Android Studio并单独打开了一个Android项目来编写Android代码,那一定要重启一下项目,刚才的依赖才会生效。完成之后,我们先新建一个类:
//这里会根据相应的注解响应对应的生命周期,可根据需要添加
interface CustomLifecycleObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {}
}
在初始的Plugin类
class FlutterNativeHelperPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
private var mActivity: Activity? = null
private var mLifecycle: Lifecycle? = null
private val mLifecycleObserver = object : CustomLifecycleObserver {
override fun onResume() {
//在这里就会回调相应的生命周期
}
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
mActivity = binding.activity
mLifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding)
mLifecycle?.addObserver(mLifecycleObserver)
}
override fun onDetachedFromActivityForConfigChanges() {
mActivity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
mActivity = binding.activity
}
override fun onDetachedFromActivity() {
mActivity = null
mLifecycle?.removeObserver(mLifecycleObserver)
mLifecycle = null
}
}
然后我们就可以开心的继续写代码了❤️