Search code examples
androidbackground-processactivity-manager

How to tell if application is in the background?


I have the following method which does not work accurately for the Lollipop code segment. The getRunningAppProcesses() method returns all sorts of system tasks and also returns multiple results which I am unable to determine which result represents the equivalent of using getRunningTasks(1).get(0).topActivity.

How is this suppose to be done for API 21 and above?

   public static boolean isAppInBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
            if (!tasks.isEmpty()) {
                for (ActivityManager.RunningAppProcessInfo fullTaskList : tasks) {
                    if (fullTaskList.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                        // NOTE: this condition needs to be changed because
                        // the list returns multiple results and not all 
                        // the results represent IMPORTANCE_BACKGROUND
                        return true;
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
            if (!tasks.isEmpty()) {
                ComponentName topActivity = tasks.get(0).topActivity;
                if (!topActivity.getPackageName().equals(context.getPackageName())) {
                    return true;
                }
            }
        }
        return false;
    }

Solution

  • The most simple and straightforward solution that I found is the following:

    public class AppStatusHelper {
        private static final String TAG = AppStatusHelper.class.getSimpleName();
    
        private static int mNumOfActivitiesInOnStarttoOnStopLifeCycle=0;
    
        public static void onStart()
        {
            mNumOfActivitiesInOnStarttoOnStopLifeCycle++;
        }
        public static void onStop()
        {
            mNumOfActivitiesInOnStarttoOnStopLifeCycle--;
        }
    
        public static boolean isAppInBackground()
        {
            Log.d(TAG,"num->"+mNumOfActivitiesInOnStarttoOnStopLifeCycle+"\tisOnBackground->"+(mNumOfActivitiesInOnStarttoOnStopLifeCycle==0));
            return mNumOfActivitiesInOnStarttoOnStopLifeCycle==0;
        }
    
    }
    

    Just call onStart on every activity start and onStop on every activity stop. Then check if the counter is equal to 0.