First add some of the following necessary dependencies in app level gradle
dependencies {
def lifecycle_version = "2.1.0"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
// alternatively - just ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" // For Kotlin use lifecycle-viewmodel-ktx
// alternatively - just LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// alternatively - Lifecycles only (no ViewModel or LiveData). Some UI
// AndroidX libraries use this lightweight import for Lifecycle
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
// optional - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version" // For Kotlin use lifecycle-reactivestreams-ktx
// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$lifecycle_version"
}
You may refer to the latest version of dependency here
https://developer.android.com/jetpack/androidx/releases/lifecycle?authuser=1
Your app must extend the Application class and override the following the methods given in example below.
You can simply achieve the same functionality using lifecycle-aware component of arch libraries. I have just posted one sample code for Kotlin and Java for your use case.
The Java version.
public class YourApp extends Application implements LifecycleObserver {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
// Application level lifecycle events
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onEnteredForeground() {
//Timber.d("Application did enter foreground");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onEnteredBackground() {
// Timber.d("Application did enter background");
}
}
Kotlin version:
class ZumeApp : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
// Application level lifecycle events
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onEnteredForeground() {
Timber.d("Application did enter foreground")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onEnteredBackground() {
Timber.d("Application did enter background")
}
}
I hope it will help you. Leave a comment if it does not work or refer to the following article in android docs.
https://developer.android.com/topic/libraries/architecture/lifecycle?authuser=1