With the new Android Architecture Components there is an easy way to know if your app is in the foreground or the background.
Just like with the activity scope lifecycle owner there is a general process lifecycle owner which you can subscribe to and get lifecycle updates.
For example:
Add this code in order to register as a lifecycle observer
ProcessLifecycleOwner.get().lifecycle.addObserver(lifecycleListener)
And this code in order to receive the relevant callbacks
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onApplicationOnStartEvent() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onApplicationOnStopEvent() {
}
Don't forget to remove the observer once you don't need it
ProcessLifecycleOwner.get().getLifecycle().removeObserver(lifecycleListener);
More information and examples can be found in this excellent article:
https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c