Android判断应用在前台还是后台运行(判断应用前后台切换)

我们的应用要获取后台运行的app的包名,主要是getRunningTasks()方法的调用,经过测试在android 2.2 到 4.4的版本都运行的很好,但是在Android 5.0 Lollipop. 中获得不到,无法得到真实的后台运行app名称
下面是运行时的代码:
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity .getPackageName();
原因是Android 5.0在API权限上作了修改:
Android L, Google has disabled getRunningTasks. Now it can only return own apps task and the home launcher.
处理方法

参考文档:http://stackoverflow.com/questions/24625936/getrunningtasks-doesnt-work-in-android-l

public class DetectCalendarLaunchRunnable implements Runnable {  
  
@Override  
public void run() {  
  String[] activePackages;  
  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {  
    activePackages = getActivePackages();  
  } else {  
    activePackages = getActivePackagesCompat();  
  }  
  if (activePackages != null) {  
    for (String activePackage : activePackages) {  
      if (activePackage.equals("com.google.android.calendar")) {  
        //Calendar app is launched, do something  
      }  
    }  
  }  
  mHandler.postDelayed(this, 1000);  
}  
  
String[] getActivePackagesCompat() {  
  final List taskInfo = mActivityManager.getRunningTasks(1);  
  final ComponentName componentName = taskInfo.get(0).topActivity;  
  final String[] activePackages = new String[1];  
  activePackages[0] = componentName.getPackageName();  
  return activePackages;  
}  
  
String[] getActivePackages() {  
  final Set activePackages = new HashSet();  
  final List processInfos = mActivityManager.getRunningAppProcesses();  
  for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {  
    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
      activePackages.addAll(Arrays.asList(processInfo.pkgList));  
    }  
  }  
  return activePackages.toArray(new String[activePackages.size()]);  
}  
}  

通过上面的方法,获取到当前运行的程序packageName,与自己的packageName比对,

可以判断app是在前台还是后台运行,判断APP是否前台切换到后台等。

你可能感兴趣的:(Android判断应用在前台还是后台运行(判断应用前后台切换))