Bootstrap

JetPack-LifeCycle

首先明确一下LifeClcle是什么:Lifecycle 是具有生命周期感知能力的组件

从继承关系可以看出通过getLifeCycle可获取到一个可感知生命周期的对象,通过在此对象中添加需要的监听,我们能在 Activity ,Fragment,Service或者Process 的生命周期发生变化的时候得到通知

以activity举例,可看出父类中定义方法返回生命周期管理对象,所以在正确的继承关系下可以直接从中获取到lifeCycle对象

一,Activity中

看个例子,自动统计用户在打开某个activity后使用了多长时间(不在前台时清零,打开重新计数),首先定义一个可被添加到生命周期管理器中的操作对象(继承LifecycleObserver接口)

class LCAtListener:LifecycleObserver {

    companion object{
        private const val TAG = "LCAtListener"
    }

    private var timeStart=0L
    private var timeEnd=0L

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onActivityResume() {
        Log.d(TAG, "onActivityResume: ")
        timeStart=SystemClock.elapsedRealtime()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onActivityDestroy(){
        Log.d(TAG, "onActivityDestroy: ")
        timeEnd=SystemClock.elapsedRealtime()
        Log.d(TAG, "timeLife:${(timeEnd-timeStart)/1000} ")
    }
    
}

在activity中获取生命周期对象进行监听器(LCAtListener)添加

class LifeCycleActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_life_cycle)

        lifecycle.addObserver(LCAtListener())
    }
}

进行测试

2021-04-16 10:18:31.657 4228-4228/com.kai.jetpack D/LCAtListener: onActivityResume: 
2021-04-16 10:18:35.656 4228-4228/com.kai.jetpack D/LCAtListener: onActivityDestroy: 
2021-04-16 10:18:35.657 4228-4228/com.kai.jetpack D/LCAtListener: timeLife:3 

二,Service中(继承LifecycleService)

class LifeService : LifecycleService() {
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
        lifecycle.addObserver(LCAtListener())
    }
}

三,process中

亦可监听自身

class MyApplication:Application(),LifecycleObserver {
    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.apply {
            addObserver(this@MyApplication)
            addObserver(LCAtListener())
        }
    }
    
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroyLog(){
        Log.d("application---", "onDestroyLog: ---")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreateLog(){
        Log.d("application---", "onCreateLog: ")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPauseLog(){
        Log.d("application---", "onPauseLog: ")
    }
}

最后附上官方文档地址https://developer.android.com/topic/libraries/architecture/lifecycle

 
;