@@ -428,32 +428,52 @@ public static boolean isSystemApp(Context context, String packageName) {
428
428
429
429
/**
430
430
* 判断App是否处于前台
431
- * <p>需添加权限 {@code <uses-permission android:name="android.permission.GET_TASKS"/>}</p>
432
- * <p>并且必须是系统应用该方法才有效</p>
433
431
*
434
432
* @param context 上下文
435
433
* @return {@code true}: 是<br>{@code false}: 否
436
434
*/
437
435
public static boolean isAppForeground (Context context ) {
438
- return isAppForeground (context , context .getPackageName ());
436
+ return isApplicationForeground (context , context .getPackageName ());
439
437
}
440
438
441
439
/**
442
440
* 判断App是否处于前台
443
441
* <p>需添加权限 {@code <uses-permission android:name="android.permission.GET_TASKS"/>}</p>
444
- * <p>并且必须是系统应用该方法才有效 </p>
442
+ * <p>该方法在 API 21 被遗弃,已经不能使用 </p>
445
443
*
446
444
* @param context 上下文
447
445
* @param packageName 包名
448
446
* @return {@code true}: 是<br>{@code false}: 否
449
447
*/
448
+ @ Deprecated
450
449
public static boolean isAppForeground (Context context , String packageName ) {
451
450
ActivityManager am = (ActivityManager ) context .getSystemService (Context .ACTIVITY_SERVICE );
452
451
@ SuppressWarnings ("deprecation" )
453
452
List <ActivityManager .RunningTaskInfo > tasks = am .getRunningTasks (1 );
454
453
return tasks != null && !tasks .isEmpty ()
455
454
&& tasks .get (0 ).topActivity .getPackageName ().equals (packageName );
456
455
}
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
+ }
457
477
458
478
/**
459
479
* 封装App信息的Bean类
0 commit comments