package com.hh.hhomc.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.hh.hhomc.BuildConfig;
import com.hh.hhomc.bean.AppInfoBean;

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

public class AppUtils {


    public static ArrayList<AppInfoBean> getAppList(Context context) {

        ArrayList<AppInfoBean> appList = new ArrayList<AppInfoBean>(); //用来存储获取的应用信息数据
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packages = packageManager.getInstalledPackages(0);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            AppInfoBean tmpInfo = new AppInfoBean();
            tmpInfo.appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
            tmpInfo.packageName = packageInfo.packageName;
            tmpInfo.versionName = packageInfo.versionName;
            tmpInfo.versionCode = packageInfo.versionCode;
//            tmpInfo.appIcon = packageInfo.applicationInfo.loadIcon(packageManager);
            appList.add(tmpInfo);
        }

        return appList;

    }


    // 根据包名判断是否已安装
    public static boolean isApkInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 根据包名启动对应app
    public static void startApp(Activity context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return;
        }
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        if (intent != null) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }

    }


}
