如何判断应用程序是否在后台?

How to tell if application is in the background?

我有以下方法不能准确地用于 Lollipop 代码段。 getRunningAppProcesses() 方法 returns 各种系统任务以及 returns 多个结果,我无法确定哪个结果代表使用 getRunningTasks(1).get(0).topActivity 的等效结果。

对于 API 21 岁及以上的人,应该怎么做?

   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;
    }

我找到的最简单直接的解决方案如下:

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;
    }

}

只需在每次 activity 开始时调用 onStart 并在每次 activity 停止时调用 onStop。然后检查计数器是否等于0.