Example of Android programming method for judging whether the current application is running in the background

  • 2021-08-28 21:11:08
  • OfStack

This paper describes the method of judging whether the current application is running in the background by Android programming. Share it for your reference, as follows:


/**  Determine whether the program is running in the background  */
public static boolean isRunBackground(Context context) {
  ActivityManager activityManager = (ActivityManager) context
      .getSystemService(Context.ACTIVITY_SERVICE);
  List<RunningAppProcessInfo> appProcesses = activityManager
      .getRunningAppProcesses();
  for (RunningAppProcessInfo appProcess : appProcesses) {
    if (appProcess.processName.equals(context.getPackageName())) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
        //  Indicates that the program is running in the background 
        return true;
      } else {
        return false;
      }
    }
  }
  return false;
}
/**  Determine whether the program is running in the foreground (currently running program)  */
public boolean isRunForeground() {
  ActivityManager activityManager = (ActivityManager) getApplicationContext()
      .getSystemService(Context.ACTIVITY_SERVICE);
  String packageName = getApplicationContext().getPackageName();
  List<RunningAppProcessInfo> appProcesses = activityManager
      .getRunningAppProcesses();
  if (appProcesses == null)
    return false;
  for (RunningAppProcessInfo appProcess : appProcesses) {
    if (appProcess.processName.equals(packageName)
        && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
      return true;//  The program runs in the foreground 
    }
  }
  return false;
}

For more readers interested in Android related content, please check out the topics on this site: "Introduction and Advanced Tutorial of Android Development", "Summary of Android Debugging Skills and Common Problem Solutions", "Summary of Android Basic Component Usage", "Summary of Android View View Skills", "Summary of Android Layout layout Skills" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: