Skip to content Skip to sidebar Skip to footer

How To Know If My Application Is In Foreground Or Background, Android?

I need to check if my application is running in background or foreground and then perform some operations relatively to it. I searched a lot and a clear solution is not available.

Solution 1:

Well this solved my issue:

privatebooleanisAppOnForeground(Context context,String appPackageName) {
    ActivityManageractivityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
        returnfalse;
    }
    finalStringpackageName= appPackageName;
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
 //                Log.e("app",appPackageName);returntrue;
        }
    }
    returnfalse;
}

Solution 2:

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

classMyApplication : Application(), LifecycleObserver {

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

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

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

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

@OnLifecycleEvent(Lifecycle.Event.ON_START)funonAppForegrounded() {

    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()

Solution 3:

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

publicclassMyAppextendsApplication { ... }

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

Solution 4:

You can check this using process lifecycle owner.

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

Solution 5:

Use the following Function to check if your application is in Background or Foreground

public static Boolean getProcessState(Context mContext) {
    ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);

    boolean noProcessOnForeground = true;
    boolean isProcessForeground = false;

    System.out.println("Checking if process: " + mContext.getApplicationInfo().processName + " is Foreground or Background");
    List<ActivityManager.RunningAppProcessInfo> current_processes = am.getRunningAppProcesses();
    for (ActivityManager.RunningAppProcessInfo appProcess : current_processes) {
        if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {

            noProcessOnForeground = false;
            if ((mContext.getApplicationInfo().processName).equalsIgnoreCase(appProcess.processName)) {

                isProcessForeground = true;
                System.out.println("Process is Foreground");
                break;
                //   Toast.makeText(getApplicationContext(), "Process is Foreground", Toast.LENGTH_SHORT).show();
            } else {


                System.out.println("Process is Background");
                //    Toast.makeText(getApplicationContext(), "Process is Background", Toast.LENGTH_SHORT).show();
                isProcessForeground = false;
                break;
            }
        }
    }

    if (noProcessOnForeground) {

        System.out.println("there is no process on foreground so setting " + mContext.getApplicationInfo().processName + " as background");
        isProcessForeground = false;
    }

    return isProcessForeground;
}

Post a Comment for "How To Know If My Application Is In Foreground Or Background, Android?"