Jetpack

💡【Jetpack】Android Lifecycle 生命週期 範例🔧

💡【Jetpack】Android Lifecycle 生命週期 範例🔧

Android Lifecycle 是 Android 平台上一個重要的技術,可以讓開發者更好地控制應用程式在各種不同狀態之間的轉換。

它提供了一系列的方法來關聯應用程式元件的生命週期變化,從而允許開發者保持應用程式的一致性和一致性。

Android Lifecycle 也可以為開發者創造更好的應用程式,並且減少資源浪費和記憶體洩漏。

本文將詳細描述 Android Lifecycle 的工作原理和範例,以及使用它的最佳做法。

文章目錄

  1. Lifecycle Application 判斷 Activity 前後台
  2. Lifecycle
  3. Developer Documents Lifecycle

1.Lifecycle Application 判斷 Activity 前後台

build.gradle
dependencies {
    def lifecycle_version = "2.5.1"
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
}
MyApplication.kt
class MyApplication : Application(), DefaultLifecycleObserver {

    override fun onCreate() {
        super<Application>.onCreate()

        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Toast.makeText(this, "前台", Toast.LENGTH_SHORT).show()
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        Toast.makeText(this, "後台", Toast.LENGTH_SHORT).show()
    }
}
AndroidManifest.xml
<application
        android:name=".MyApplication">
</application>

2.Lifecycle

MyObserver.kt
class MyObserver : DefaultLifecycleObserver {

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        Log.e(MyObserver::class.java.simpleName, "onCreate")
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Log.e(MyObserver::class.java.simpleName, "onStart")
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        Log.e(MyObserver::class.java.simpleName, "onResume")
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        Log.e(MyObserver::class.java.simpleName, "onPause")
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        Log.e(MyObserver::class.java.simpleName, "onStop")
    }

    override fun onDestroy(owner: LifecycleOwner) {
        Log.e(MyObserver::class.java.simpleName, "onDestroy")
        super.onDestroy(owner)
    }
}
MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        lifecycle.addObserver(MyObserver())
    }
}

3.Developer Documents Lifecycle

Open in Documents Lifecycle

發表迴響