Android判断当前App是在前台还是在后台
本文实例为大家分享了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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)