Android X Lifecycle

Lifecycle Extension

From Android X, new lifecycle library comes(lifecycle-extension).

This library has powerful feature to hook lifecycle event not to override onXxxxx.

This entry introduces one of features.

build.gradle

There are several sets of this library. In this time, use root library

dependencies {
   implementation "androidx.lifecycle:lifecycle-extensions:2.2.0-alpha05"
}

What we want to do

Hook Android general lifecycle event without overriding general Android Lifecycle events onXxxx. (Except for onCreate)

LifecycleObserver

Extends this class and implement events one by one

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

class CustomLifeCycleObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        println("ON_CREATE")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart() {
        println("ON_START")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop() {
        println("ON_STOP")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        println("ON_PAUSE")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        println("ON_RESUME")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestory() {
        println("ON_DESTROY")
    }
}

Activity

Bind events from main Activity. In this time, This Activity should be extended “LifecycleOwner”.

The easiest way is to extend AppCompatActivity.

class LifecycleActivity3 : AppCompatActivity() {

    // AppCompatActivity
    // LifecycleOwner https://developer.android.com/reference/android/arch/lifecycle/LifecycleOwner

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_basic)
        lifecycle.addObserver(CustomLifeCycleObserver())
        ContextLifeCycleObserver(this, this)
    }
}

After this, you can hook events (print message each lifecycle timing)

Ref

This is a good example.

Android
スポンサーリンク
Professional Programmer2

コメント