1.判断是否运行
<uses-permission android:name="android.permission.GET_TASKS" />
static boolean isAppRunning(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> list = null; if (activityManager != null) { list = activityManager.getRunningTasks(100); } if (list == null || list.size() <= 0) { return false; } for (ActivityManager.RunningTaskInfo info : list) { if (info.baseActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }
2.判断是否在前台
private static boolean isAppForeground(Context context) { if (context != null) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> processes; if (activityManager != null) { processes = activityManager.getRunningAppProcesses(); } else { return false; } for (ActivityManager.RunningAppProcessInfo processInfo : processes) { if (processInfo.processName.equals(context.getPackageName())) { MLog.i(FaceDetectionApp.TAG, "processInfo.importance = " + processInfo.importance); if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } } } return false; }
3.判断是否在后台
通过1和2 可以判断后台