Android生命周期感知组件Lifecycle

一、概述

Lifecycle生命周期感知组件,是为了监听具有生命周期的组件的生命周期的变化。当组件(Activity/Fragment)生命周期发生变化时,观察者中事件对应方法会被回调。在观察者回调方法中可以做与组件(Activity/Fragment)生命周期变化对应的资源或者业务逻辑的处理(如,activity走了ondestroy后,观察者回调到事件ON_DESTROY后,在对应方法下做释放资源等操作)。观察者中监听回调方法也可以被其他对象监听,再做相应的处理。

二,组成

生命周期感知组件由三部分组成:

LifecycleOberver——组件生命周期变化监听者或观察者

LifecycleOwner——具有生命周期的组件需实现的接口(即,拥有生命周期的组件如Activity/Fragment)

Lifcycle——LifecycleOberver和LifecycleOwner之间实现感知生命周期变化的桥梁

三、代码实现

1、LifecycleOwner实现类:

class TestActivity : Activity(), LifecycleRegistryOwner {
    val TAG = "TestActivity"
    var mLifecycleRegistry = LifecycleRegistry(this)//创建Lifecycle对象
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "Activity#onCreate");
        setContentView(R.layout.layout_test)
        lifecycle.addObserver(MyLifecycleObserver())//添加观察者监听生命周期的变化
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "Activity#onResume");
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "Activity#onPause");
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "Activity#onDestroy");
    }

    override fun getLifecycle(): LifecycleRegistry {//获取Lifecycle对象
        return mLifecycleRegistry
    }
}

2、LifecycleOberver观察者类

class MyLifecycleObserver: LifecycleObserver {
    val TAG = "MyLifecycleObserver"
    //在如下create,resume等回调方法里可以做跟生命周期方法变化相关联的业务逻辑或者界面逻辑的处理
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun create(){
        Log.d(TAG, "Lifecycle observer call create======");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume(){
        Log.d(TAG, "Lifecycle observer call resume========");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pause(){
        Log.d(TAG, "Lifecycle observer call pause===========");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun destroy(){
        Log.d(TAG, "Lifecycle observer call destroy======");
    }

}

3、上述代码运行输出结果如下

  Activity#onCreate
  Lifecycle observer call create======
  Activity#onResume:STARTED
  Lifecycle observer call resume========
  Lifecycle observer call pause===========
  Activity#onPause

Lifecycle observer call destroy======
  Activity#onDestroy

你可能感兴趣的:(android)