LifeCycle库主要包括3部分
- Lifecycle owners, 即拥有(因而“拥有”)生命周期的组件。 Activity和Fragment是生命周期所有者。 生命周期所有者实现LifecycleOwner接口。
- Lifecycle 该类保存生命周期所有者的实际状态,并在发生生命周期更改时触发事件。
- Lifecycle observers 观察生命周期状态并在生命周期改变时执行任务。 生命周期观察者实现LifecycleObserver接口。
举个栗子: 有一个功能,计算应用在前台的时长,有个DessertTimer类
class DessertTimer {
// The number of seconds counted since the timer started
var secondsCount = 0
/**
* [Handler] is a class meant to process a queue of messages (known as [android.os.Message]s)
* or actions (known as [Runnable]s)
*/
private var handler = Handler()
private lateinit var runnable: Runnable
fun startTimer() {
// Create the runnable action, which prints out a log and increments the seconds counter
runnable = Runnable {
secondsCount++
Timber.i("Timer is at : $secondsCount")
// postDelayed re-adds the action to the queue of actions the Handler is cycling
// through. The delayMillis param tells the handler to run the runnable in
// 1 second (1000ms)
handler.postDelayed(runnable, 1000)
}
// This is what initially starts the timer
handler.postDelayed(runnable, 1000)
// Note that the Thread the handler runs on is determined by a class called Looper.
// In this case, no looper is defined, and it defaults to the main or UI thread.
}
fun stopTimer() {
// Removes all pending posts of runnable from the handler's queue, effectively stopping the
// timer
handler.removeCallbacks(runnable)
}
那么我们可以在一个Activity的onStrat方法中,调用DessertTimer的startTimer方法,在onStop中调用stopTimer方法,这么写本身没有问题,但是在更复杂的Android应用中,您可能会在onStart()或onCreate()中设置很多东西,然后在onStop()或onDestroy()中将它们全部解除。 例如,您可能需要设置,拆除,启动和停止的动画,音乐,传感器或计时器。但是如果忘记了可能就有头疼的问题产生了。 那么LifeCycle就派上用场了。
- 将DessertTimer转换为LifecycleObserver
class DessertTimer(lifecycle: Lifecycle) : LifecycleObserver {
- 初始化LIfeCycle
init {
lifecycle.addObserver(this)
}
- 添加 @OnLifecycleEvent 注解
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun startTimer() {}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stopTimer(){}
4.在调用处传入lifeCycle
dessertTimer = DessertTimer(this.lifecycle)