package cc.winboll.studio.contacts.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import java.util.List;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/12/12 15:20
 * @Describe AppForegroundUtils 应用前后台状态判断工具类（兼容 Java 7）
 */
public class AppForegroundUtils {

    public static final String TAG = "AppForegroundUtils";

    /**
     * 判断应用是否处于前台状态
     * @param context 上下文
     * @return true-前台，false-后台/无上下文
     */
    public static boolean isAppForeground(Context context) {
        if (context == null) {
            return false;
        }

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            return false;
        }

        String packageName = context.getPackageName();
        List<ActivityManager.RunningAppProcessInfo> processList = activityManager.getRunningAppProcesses();
        if (processList == null || processList.isEmpty()) {
            return false;
        }

        // 遍历进程列表，匹配当前应用包名并判断前台状态
        for (ActivityManager.RunningAppProcessInfo processInfo : processList) {
            // Java 7 兼容：避免 Lambda，使用普通循环 + TextUtils 判等
            if (!TextUtils.isEmpty(processInfo.processName) 
				&& TextUtils.equals(processInfo.processName, packageName)
				&& processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }
}

