Android two ways to determine whether the current application is in the foreground or the background

  • 2020-05-24 06:07:29
  • OfStack

1. Judge by class RunningTaskInfo (additional permissions are required) :


/**
     * Determine whether the current application is in the foreground or background 
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

You need to add the following permissions to the AndroidMenitfest.xml file


<uses-permission android:name="android.permission.GET_TASKS" />  

2. Judge by RunningAppProcessInfo class (no additional permission is required) :


public static boolean isBackground(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) {
                          Log.i(" The background ", appProcess.processName);
                          return true;
                }else{
                          Log.i(" The front desk ", appProcess.processName);
                          return false;
                }
           }
    }
    return false;
}


Related articles: