in app gradle:
//Lifecycles only (no ViewModel or LiveData) not working at the moment... implementation "android.arch.lifecycle:extensions:1.1.1" annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
create a class:
public class AppLifecycleObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) public void onMoveToForeground() { Log.d("AppLifecycleObserver", "Returning to foreground…"); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onMoveToBackground() { Log.d("AppLifecycleObserver", "Moving to background…"); } }
initialize the AppLifecycleObserver in your app Application:
public class AppApplication extends Application { private AppLifecycleObserver appLifecycleObserver = new AppLifecycleObserver(); @Override public void onCreate() { super.onCreate(); setupLifecycleObserver(); } private void setupLifecycleObserver() { ProcessLifecycleOwner .get() .getLifecycle() .addObserver(appLifecycleObserver); } }
and finally, declare the AppApplication in the manifest
<application android:name=".AppApplication"
source: https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c