Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check android application is in foreground or not? [duplicate]

Tags:

android

People also ask

How do you tell if an app is running in the background Android?

If you don't want the app to relaunch when you restart your phone, tap Uninstall to remove the app. To see what apps are running in the background, go to Settings > Developer Options > Running Services.

What is app foreground activity?

Foreground refers to the active apps which consume data and are currently running on the mobile. Background refers to the data used when the app is doing some activity in the background, which is not active right now.


I don't understand what you want, but You can detect currently foreground/background application with ActivityManager.getRunningAppProcesses() call.

Something like,

class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

  @Override
  protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
  }

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

// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();

Also let me know if I misunderstand..

UPDATE: Look at this SO question Determining the current foreground application from a background task or service fore more information..

Thanks..


Update Oct 2020: Checkout the Lifecycle extensions based solutions on this thread. The approach seems to be working, it's more elegant and modern.


The neatest and not deprecated way that I've found so far to do this, as follows:

@Override
public boolean foregrounded() {
    ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
    ActivityManager.getMyMemoryState(appProcessInfo);
    return (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
}

It only works with SDK 16+.

EDIT:

I removed the following code from the solution:

KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
// App is foreground, but screen is locked, so show notification
return km.inKeyguardRestrictedInputMode();

since that makes not getting the notifications if the screen locked. I had a look to the framework and the purpose of this is not entirely clear. I'd remove it. Checking the process info state would be enough :-)


@user370305's answer is error prone and discouraged by Android OS Developers (check https://groups.google.com/forum/#!msg/android-developers/zH-2bovZSLg/L2YM8Z1N-HwJ)

There is a much more simpler approach:

On a BaseActivity that all Activities extend:

protected static boolean isVisible = false;

@Override
public void onResume() {
   super.onResume();
   setVisible(true);
}

@Override
public void onPause() {
    super.onPause();
    setVisible(false);
}

Whenever you need to check if any of your application activities is in foreground just check isVisible();

To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle


With the new Android Architecture of Lifecycle extensions, we can achieve this with utmost ease.

Just ensure you pull this dependency in your build.gradle file:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.0"
}

Then in your Application class, use this:

class ArchLifecycleApp : Application(), LifecycleObserver {

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

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        Log.d("MyApp", "App in background")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        Log.d("MyApp", "App in foreground")
    }
}

In the end, update your AndroidManifest.xml file with:

<application
    android:name=".ArchLifecycleApp"
    //Your extra code
    ....>
</application>

Now, on everytime the Application goes to Foreground or Background, we are going to receive the Logs associated with the two methods declared.


Android Architecture Components library you can use the ProcessLifecycleOwner to set up a listener to the whole application process for onStart and onStop events. To do this, make your application class implement the LifecycleObserver interface and add some annotations for onStart and onStop to your foreground and background methods.

class ArchLifecycleApp : Application(), LifecycleObserver {

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

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        Log.d("Awww", "App in background")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        Log.d("Yeeey", "App in foreground")
    }

}

I have tried with package filter from running process. but that is very weird. Instead of that, I have try new solution and this work perfectly. I have checked many times and getting perfect result through this module.

private int numRunningActivities = 0;

 public void onCreate() {
        super.onCreate();
this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

                @Override
                public void onActivityStarted(Activity activity) {
                    numRunningActivities++;
                    if (numRunningActivities == 1) {
                        LogUtils.d("APPLICATION", "APP IN FOREGROUND");
                    }

                }

                @Override
                public void onActivityStopped(Activity activity) {

                    numRunningActivities--;
                    if (numRunningActivities == 0) {
                       Log.e("", "App is in BACKGROUND") 
                    }
                }


                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                }

                @Override
                public void onActivityResumed(Activity activity) {
                }

                @Override
                public void onActivityPaused(Activity activity) {
                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                }

                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                }
            });
}