Android Lollipop 5.0 获取后台运行的APP包名


我们的应用要获取后台运行的app的包名,主要是getRunningTasks()方法的调用,经过测试在android 2.2 到 4.4的版本都运行的很好,但是在Android 5.0 Lollipop. 中获得不到,无法得到真实的后台运行app名称,在Android 5.0 Lollipop中获得的名称是 'Launcher3',我使用过的模拟器是  Genymotion Emulator。


下面是运行时的代码:


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<ActivityManager.RunningTaskInfo> 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<String> activePackages = new HashSet<String>();
  final List<ActivityManager.RunningAppProcessInfo> 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()]);
}
}


 

你可能感兴趣的:(android,后台运行,android5.0)