lifecycle极大的对UI组件的声明周期进行了解耦。
依赖:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
代码演示:
ActivityLifecycleObserver.kt
class ActivityLifecycleObserver : DefaultLifecycleObserver {private val TAG = "ActivityLifecycleObserver"override fun onCreate(owner: LifecycleOwner) {super.onCreate(owner)Log.i(TAG,"onCreate")}override fun onDestroy(owner: LifecycleOwner) {super.onDestroy(owner)Log.i(TAG,"onDestroy")}override fun onPause(owner: LifecycleOwner) {super.onPause(owner)Log.i(TAG,"onPause")}override fun onResume(owner: LifecycleOwner) {super.onResume(owner)Log.i(TAG,"onResume")}override fun onStart(owner: LifecycleOwner) {super.onStart(owner)Log.i(TAG,"onStart")}override fun onStop(owner: LifecycleOwner) {super.onStop(owner)Log.i(TAG,"onStop")}
}
将一个自定义类变成一个lifecycle观察者有两种方法。
第一种方法是上述代码所演示的DefaultLifecycleObserver。
第二种方法是实现LifecycleObserver接口,并且每个方法上添加注释
@OnLifecycleEvent(Lifecycle.Event.enum)(其中的enum代表Event中的枚举值)
public enum class Event {/*** Constant for onCreate event of the [LifecycleOwner].*/ON_CREATE,/*** Constant for onStart event of the [LifecycleOwner].*/ON_START,/*** Constant for onResume event of the [LifecycleOwner].*/ON_RESUME,/*** Constant for onPause event of the [LifecycleOwner].*/ON_PAUSE,/*** Constant for onStop event of the [LifecycleOwner].*/ON_STOP,/*** Constant for onDestroy event of the [LifecycleOwner].*/ON_DESTROY,/*** An [Event] constant that can be used to match all events.*/ON_ANY;
}
这两种方法中我还是比较推荐继承DefaultLifecycleObserver😋。因为,第二种方法是利用反射的原理取实现的,会增加性能开销。
Activity中的操作:
class MainActivity : AppCompatActivity() {private lateinit var activityObserver: ActivityLifecycleObserveroverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)activityObserver = ActivityLifecycleObserver()lifecycle.addObserver(activityObserver)}
}
在AppCompatActivity和Fragment中都继承了LifecycleOwner。这就和lifecycle的原理有关了,下个博客里面在讲。如上述代码,就能够将observer中声明在不同生命周期的操作与activity的生命周期绑定在一起,licycleobserver通过观察MainActivity的生命周期的变化,去执行相应的代码操作。
如果觉得主包讲的不错的可以给个关注哦😚