时间:2020-10-06 21:54:35 | 栏目:Android代码 | 点击:次
本文实例为大家分享了Android判断当前App状态的具体实现代码,供大家参考,具体内容如下
第一种:
/** *判断当前应用程序处于前台还是后台 * * @param context * @return */ 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; }
上面这段代码是需要一个权限的:
< uses-permission Android:name=”android.permission.GET_TASKS” />
第二种:
下面这段代码是我最新发现,无需权限,妥妥滴:
不过我稍微做了调整,后台分为:service后台和activity后台,这里认为不是前台的都认为后台。
•service运行在后台,appProcess.importance = IMPORTANCE_SERVICE,
•没有service运行的后台,
public static boolean isBackground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.processName.equals(context.getPackageName())) { if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { System.out.print(String.format("Foreground App:", appProcess.processName)); return false; }else{ System.out.print("Background App:"+appProcess.processName); return true; } } } return false; }