How to know if my application is in foreground or background, android?

Original Answer : https://stackoverflow.com/a/60212452/10004454 The recommended way to do it in accordance with Android documentation is

class MyApplication : Application(), LifecycleObserver {

override fun onCreate() {
    super.onCreate()
    ProcessLifecycleOwner.get().lifecycle.addObserver(this);
}

fun isActivityVisible(): String {
    return ProcessLifecycleOwner.get().lifecycle.currentState.name
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
    //App in background

    Log.e(TAG, "************* backgrounded")
    Log.e(TAG, "************* ${isActivityVisible()}")
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {

    Log.e(TAG, "************* foregrounded")
    Log.e(TAG, "************* ${isActivityVisible()}")
    // App in foreground
}}

In your gradle (app) add : implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

Then to check the state at runtime call MyApplication().isActivityVisible()


Well this solved my issue:

  private boolean isAppOnForeground(Context context,String appPackageName) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
        return false;
    }
    final String packageName = appPackageName;
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
 //                Log.e("app",appPackageName);
            return true;
        }
    }
    return false;
}

You can check this using process lifecycle owner.

fun isAppOnForeground(): Boolean {
return ProcessLifecycleOwner.get().getLifecycle().getCurrentState()
    .isAtLeast(Lifecycle.State.STARTED);
}

use AppVisibilityDetector, I implement this class to detect the app visibility status. it can detect the foreground and background status and perform the callback method.

 AppVisibilityDetector.init(MyApp.this, new AppVisibilityCallback() {
    @Override
    public void onAppGotoForeground() {
        //app is from background to foreground
    }
    @Override
    public void onAppGotoBackground() {
        //app is from foreground to background
    }
});

the MyApp is your Application class

public class MyApp extends Application { ... }

you don't need add some other codes to your Activity or any permissions in the AndroidManifest.xml