判断应用是否处于前台
private boolean isForeground() { ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses(); if (processes == null || processes.isEmpty()) { return false; } for (ActivityManager.RunningAppProcessInfo info : processes) { if (info.processName.equals(getPackageName()) && info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } return false; }