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

时间:2015-09-03 00:51:15

标签: android background-process activity-manager

我有以下方法对Lollipop代码段无法正常工作。 getRunningAppProcesses()方法返回所有类型的系统任务,并返回多个结果,我无法确定哪个结果代表使用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;
    }

1 个答案:

答案 0 :(得分:1)

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

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

}

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