Android 判断APP前台,后台运行

public void checkAppState() {
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

String[] activePackages;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
activePackages = getActivePackages(am);
} else {
activePackages = getActivePackagesCompat(am);
}
if (activePackages != null) {
for (String activePackage : activePackages) {
if (activePackage.equals(getPackageName())) {
//Calendar app is launched, do something
}else{

}
}
}
}

protected String[] getActivePackagesCompat(ActivityManager mActivityManager) {
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;
}

protected String[] getActivePackages(ActivityManager mActivityManager) {
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()]);
}
posted @ 2017-07-11 09:59  农民子弟  阅读(507)  评论(0编辑  收藏  举报