@@ -428,32 +428,52 @@ public static boolean isSystemApp(Context context, String packageName) {
428428
429429 /**
430430 * 判断App是否处于前台
431- * <p>需添加权限 {@code <uses-permission android:name="android.permission.GET_TASKS"/>}</p>
432- * <p>并且必须是系统应用该方法才有效</p>
433431 *
434432 * @param context 上下文
435433 * @return {@code true}: 是<br>{@code false}: 否
436434 */
437435 public static boolean isAppForeground (Context context ) {
438- return isAppForeground (context , context .getPackageName ());
436+ return isApplicationForeground (context , context .getPackageName ());
439437 }
440438
441439 /**
442440 * 判断App是否处于前台
443441 * <p>需添加权限 {@code <uses-permission android:name="android.permission.GET_TASKS"/>}</p>
444- * <p>并且必须是系统应用该方法才有效 </p>
442+ * <p>该方法在 API 21 被遗弃,已经不能使用 </p>
445443 *
446444 * @param context 上下文
447445 * @param packageName 包名
448446 * @return {@code true}: 是<br>{@code false}: 否
449447 */
448+ @ Deprecated
450449 public static boolean isAppForeground (Context context , String packageName ) {
451450 ActivityManager am = (ActivityManager ) context .getSystemService (Context .ACTIVITY_SERVICE );
452451 @ SuppressWarnings ("deprecation" )
453452 List <ActivityManager .RunningTaskInfo > tasks = am .getRunningTasks (1 );
454453 return tasks != null && !tasks .isEmpty ()
455454 && tasks .get (0 ).topActivity .getPackageName ().equals (packageName );
456455 }
456+
457+ /**
458+ * 判断 App 是否处于前台
459+ *
460+ * @param context 上下文
461+ * @param packageName 包名
462+ * @return {@code true}: 是<br>{@code false}: 否
463+ */
464+ public static boolean isApplicationForeground (final Context context , String packageName ) {
465+ final ActivityManager am = (ActivityManager ) context .getSystemService (Context .ACTIVITY_SERVICE );
466+ final List <ActivityManager .RunningAppProcessInfo > processInfos = am .getRunningAppProcesses ();
467+ if (processInfos != null ) {
468+ for (ActivityManager .RunningAppProcessInfo processInfo : processInfos ) {
469+ if (processInfo .importance == ActivityManager .RunningAppProcessInfo .IMPORTANCE_FOREGROUND
470+ && Arrays .asList (processInfo .pkgList ).contains (packageName )) {
471+ return true ;
472+ }
473+ }
474+ }
475+ return false ;
476+ }
457477
458478 /**
459479 * 封装App信息的Bean类
0 commit comments