概要
androidx.lifecycle:2.2.0
からライフサイクルのイベントをオブザーバー経由で受け取れるようになったため実装のメモ
環境
- targetSdkVersion: 29
- kotlin: 1.3.72
- androidx.appcompat:appcompat: 1.1.0
実装
LifecycleEventObserver
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) lifecycle.addObserver(LifecycleEventObserver { source, event -> when (event) { Lifecycle.Event.ON_CREATE -> { Log.d("MainActivity", "on_create") } Lifecycle.Event.ON_START -> { Log.d("MainActivity", "on_start") } Lifecycle.Event.ON_RESUME -> { Log.d("MainActivity", "on_resume") } Lifecycle.Event.ON_PAUSE -> { Log.d("MainActivity", "on_pause") } Lifecycle.Event.ON_STOP -> { Log.d("MainActivity", "on_stop") } Lifecycle.Event.ON_DESTROY -> { Log.d("MainActivity", "on_destroy") } else -> Log.d("MainActivity", "other") } }) } }
LifecycleOvserver を使った書き方
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.lifecycle.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) lifecycle.addObserver(object: LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { Log.d("MainActivity", "onCreate") } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResume() { Log.d("MainActivity", "onResume") } @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { Log.d("MainActivity", "onStart") } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { Log.d("MainActivity", "onStop") } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun onPause() { Log.d("MainActivity", "onPause") } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { Log.d("MainActivity", "onDestroy") } @OnLifecycleEvent(Lifecycle.Event.ON_ANY) fun onAny(source: LifecycleOwner, event: Lifecycle.Event) { Log.d("MainActivity", "onAny: $event") } }) } }
androidx.appcompat
自体にLifecycle自体はすでに組み込まれているようで、パッケージのインポートは特に不要なようです。