Assume you are using AndroidX for your project, then you can use ProcessLifecycleOwner to determine the app has gone or appeared on the screen.
ProcessLifecycleOwner
Class that provides lifecycle for the whole application process.
It is useful for use cases where you would like to react on your app
coming to the foreground or going to the background and you don't need
a milliseconds accuracy in receiving lifecycle events.
Using in your code:
1.Create a class that extends from Application class.
public class MyApplication extends Application {
private final MyLifecycleObserver observer = new MyLifecycleObserver();
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(observer);
}
class MyLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppMoveToForeground() {
Log.d("MyLifecycleObserver", "My app moves to foreground.");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveAppToBackground() {
Log.d("MyLifecycleObserver", "My app moves to background.");
}
}
}
2.Add android:name=".MyApplication"
in your AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidx">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>