LifeCycle ライブラリは 3 つの主要な部分で構成されています。
- ライフサイクルの所有者、つまりライフサイクルを持つコンポーネント。 アクティビティとフラグメントはライフサイクルオーナーです。 ライフサイクルオーナーは LifecycleOwner インターフェースを実装します。
- Lifecycle このクラスは、ライフサイクル・オーナーの実際の状態を保持し、ライフサイクルの変更が発生したときにイベントをトリガーします。
- ライフサイクルオブザーバは、ライフサイクルの状態を監視し、ライフサイクルが変化したときにタスクを実行します。 ライフサイクルオブザーバーは 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)
}
このように書いても本来は問題ないのですが、より複雑なAndroidアプリの場合、onStartでいろいろなことを設定し、onStopでそのすべてを解除することになります。onStopでそれらをすべて終了させます。 例えば、アニメーション、音楽、センサー、タイマーなどを設定したり、停止したり、開始したり、終了したりする必要があるかもしれません。しかし、忘れると頭痛の種になるかもしれません。そこで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)