在某些情況下,我們可能需要偵測 app 何時進入背景或前景。例如,我們想要知道使用者花多少時間使用了我們的 app。所以當 app 進入背景或前景時,我們會傳送一個 timestamp 給 server。Server 就可以分析這些 timestamp,來計算出使用者使用 app 的時間。
ProcessLifecycleOwner 為整個 application process 提供了 lifecycle。因此,我們可以向 ProcessLifecycleOwner 註冊一個 DefaultLifecycleObserver,來監聽 app 的 lifecycle 的變化。
想要使用 ProcessLifecycleOwner,必須要先引入以下的依賴。
dependencies {
implementation 'androidx.lifecycle:lifecycle-process:2.5.1'
}然後,我們要宣告一個 Application,並在 onCreate() 中,向 ProcessLifecycleOwner 註冊一個 DefaultLifecycleObserver。
當 app 進入背景時,DefaultLifecycleObserver.onStop() 就會被呼叫。而,當 app 進入前景時,DefaultLifecycleObserver.onStart() 就會被呼叫。這包含當你啟動 app,然後 app 顯示到前景。
import android.app.Application
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
class MyApplication : Application() {
companion object {
private const val TAG = "MyApplication"
}
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
Log.d(TAG, "Detected app's going to foreground")
}
override fun onStop(owner: LifecycleOwner) {
Log.d(TAG, "Detected app's going to background")
}
})
}
}最後,在 AndroidManifest.xml 中,在 <application> 標籤裡,指定使用我們剛剛建立的 MyApplication。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:name=".MyApplication"
...>
<activity ...>
</activity>
</application>
</manifest>這樣就大功告成了!是不是相當地簡單!









