package com.xhly.corelib.utils;

import static com.xhly.corelib.utils.BaseUtilsKt.LogShow;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;


import com.xhly.corelib.bean.AppInfo;

import java.util.ArrayList;
import java.util.List;

public class AppUtils {
    public static List<AppInfo> GetAppList(Context context) {
        List<AppInfo> list = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> activities = pm.queryIntentActivities(mainIntent, 0);
        for (ResolveInfo info : activities) {
            String packName = info.activityInfo.packageName;
            LogShow("数据","数据类名" + packName+"|||"+info.activityInfo.name);
            if (packName.equals(context.getPackageName())) {
                continue;
            }
            AppInfo mInfo = new AppInfo();
            mInfo.setIco(info.activityInfo.applicationInfo.loadIcon(pm));
            mInfo.setName(info.activityInfo.applicationInfo.loadLabel(pm).toString());
            mInfo.setPackageName(packName);
            try {
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packName, PackageManager.GET_META_DATA);
                 mInfo.setVersionName(packageInfo.versionName);
                 mInfo.setVersionNum(packageInfo.versionCode);
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(e);
            }
            // 为应用程序的启动Activity 准备Intent
            Intent launchIntent = new Intent();
            launchIntent.setComponent(new ComponentName(packName,
                    info.activityInfo.name));
            mInfo.setIntent(launchIntent);
            list.add(mInfo);
        }
        return list;
    }
}