Android判断当前App状态 Android判断当前App是在前台还是在后台
xx326664162 人气:0想了解Android判断当前App是在前台还是在后台的相关内容吗,xx326664162在本文为您仔细讲解Android判断当前App状态的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:android判断app状态,android判断后台运行,android判断前台运行,下面大家一起来学习吧。
第一种:
/** *判断当前应用程序处于前台还是后台 * * @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; }
加载全部内容