在android 5.0以上,如何判断当前应用是在前台还是后台

今天在做项目时遇到这个问题,本来很简单的,但是在Android 5.1 的系统上运行却出错了,在网上查找答案后发现原来是在android 5.0 之后getRunningTask()方法被废弃,失效了。在网上查到的解决方法如下,已验证有效:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. private boolean isAppIsInBackground(Context context) {  
  2.        boolean isInBackground = true;  
  3.        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);  
  4.        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {  
  5.            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();  
  6.            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {  
  7.                //前台程序  
  8.                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
  9.                    for (String activeProcess : processInfo.pkgList) {  
  10.                        if (activeProcess.equals(context.getPackageName())) {  
  11.                            isInBackground = false;  
  12.                        }  
  13.                    }  
  14.                }  
  15.            }  
  16.        } else {  
  17.            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);  
  18.            ComponentName componentInfo = taskInfo.get(0).topActivity;  
  19.            if (componentInfo.getPackageName().equals(context.getPackageName())) {  
  20.                isInBackground = false;  
  21.            }  
  22.        }  
  23.   
  24.        return isInBackground;  
  25.    }  
posted @ 2017-01-22 10:32  dongweiq  阅读(5887)  评论(0编辑  收藏  举报