With the new Android Architecture of Lifecycle extensions, we can achieve this with utmost ease.
Just ensure you pull this dependency in your build.gradle file:
dependencies {
implementation "android.arch.lifecycle:extensions:1.1.0"
}
Then in your Application class, use this:
class ArchLifecycleApp : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
Log.d("MyApp", "App in background")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
Log.d("MyApp", "App in foreground")
}
}
In the end, update your AndroidManifest.xml file with:
<application
android:name=".ArchLifecycleApp"
//Your extra code
....>
</application>
Now, on everytime the Application goes to Foreground or Background, we are going to receive the Logs associated with the two methods declared.