本文实例为大家分享了Android判断当前App状态的具体实现代码,供大家参考,具体内容如下
第一种:
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;
}
您可能感兴趣的文章:Android 中 ActivityLifecycleCallbacks的实例详解Android判断App前台运行还是后台运行(运行状态)Android编程判断当前指定App是否在前台的方法ActivityLifecycleCallbacks如何判断APP是否在前台