1. 程式人生 > >android 如何判斷應用在前臺

android 如何判斷應用在前臺

private boolean isAppOnForeground() {
    ActivityManager activityManager = (ActivityManager) mContext.getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);
    String packageName = mContext.getApplicationContext().getPackageName();
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
        return false;
    }
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.processName.equals(packageName)
                && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            return true;
        }
    }
    return false;
}