Android工具大杂烩

来吧来吧,今天闲着有空。暂时没想到要写什么好。等之后把所做的项目都整理一下看看。

那今天就把我用过整理过的Android项目上的工具类收集整理一下。

/**
     * 判断本机是否安装了某个应用程序
     * 
     * @param context
     *            Context对象
     * @param packagename
     *            目标应用程序的包名
     * @return true表示已安装,false表示未安装
     */
    public static boolean isAppInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }
/**
     * 获取版本号
     * 
     * @param context
     *            Context对象
     * @return 版本号
     */
    public static int getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        int versionCode = 0;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
/**
     * 获取版本名
     * 
     * @param context
     *            Context对象
     * @return 版本名
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
/**
     * 安装apk
     * 
     * @param context
     *            Context对象
     * @param apkFile
     *            apk文件
     */
    public static void installApp(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(apkFile);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
/**
     * 返回所有应用的名称
     * 
     * @param context
     *            Context对象
     * @return 应用程序集合
     */
    public static List<String> getInstalledInfo(Context context) {
        List<String> list = new ArrayList<String>();
        List<PackageInfo> ps = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo packageInfo : ps) {
            list.add(packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString());
        }
        return list;
    }
/**
     * 获取设备名称 <br>
     * 比如:SAMSUNG9300、LEX720
     * 
     * @return 设备名称
     */
    public static String getPhoneType() {
        return android.os.Build.MODEL;
    }
/**
     * 获取Android sdk版本 <br>
     * 比如:android4.3、android6.0
     * 
     * @return android sdk版本
     */
    public static String getAndroidSdkVersionName() {
        return "android" + android.os.Build.VERSION.RELEASE;
    }
/**
     * 获取手机厂商
     * 
     * @return 手机厂商
     */
    public static String getPhoneManufacture() {
        return android.os.Build.MANUFACTURER;
    }
/**
     * 获取设备的IMEI
     * 
     * @param context
     *            Context对象
     * @return 设备IMEI
     */
    public static String getImei(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }
/**
     * 获取设备唯一id
     * 
     * @param context
     *            Context对象
     * @return 设备唯一id
     */
    public static String getUniqueId(Context context) {
        String imei = getImei(context);
        if (!TextUtils.isEmpty(imei))
            return imei;
        else {
            String phoneId = getPhoneId(context);
            if (!TextUtils.isEmpty(phoneId))
                return phoneId;
        }
        return "unknow";
    }
/**
     * 获取cpu信息
     * 
     * @return cpu信息
     */
    public static String[] getCpuInfo() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String[] cpuInfo = { "", "" };
        String[] arrayOfString;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            for (int i = 2; i < arrayOfString.length; i++) {
                cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
            }
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            cpuInfo[1] += arrayOfString[2];
            localBufferedReader.close();
            fr.close();
        } catch (IOException e) {
        }
        return cpuInfo;
    }
/**
     * 获取SDCard大小
     * 
     * @param context
     *            Context对象
     * @return SDCard大小
     */
    public static String getSDTotalSize(Context context) {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return Formatter.formatFileSize(context, blockSize * totalBlocks);
        }
        return "unknow";
    }
public class NetworkUtil {
    /**
     * 判断是否有网络连接
     * 
     * @param context
     *            Context对象
     * @return true表示有网络,false表示没有网络
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断WIFI网络是否可用
     * 
     * @param context
     *            Context对象
     * @return true表示wifi可用,false表示WiFi不可用
     */
    @SuppressWarnings("deprecation")
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断MOBILE网络是否可用
     * 
     * @param context
     *            Context对象
     * @return true表示可用,false表示不可用
     */
    @SuppressWarnings("deprecation")
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 获取当前网络连接的类型信息
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

    /**
     * 获取当前网络类型
     * 
     * @param context
     *            Context对象
     * @return 2G/3G/4G/WIFI/NULL/unknown
     */
    public static String getNetType(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null || !info.isAvailable()) {
            return "no";
        }
        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            return "WIFI";
        }
        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            int sub = info.getSubtype();
            switch (sub) {

            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_CDMA:// 电信的2G
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                // 以上的都是2G网络
                return "2G";

            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                // 以上的都是3G网络
                return "3G";

            case TelephonyManager.NETWORK_TYPE_LTE:

                return "4G";

            case TelephonyManager.NETWORK_TYPE_UNKNOWN:

                return "unknown";

            default:
                return "unknown";
            }
        }
        return "unknown";
    }

    /**
     * 获取MAC地址
     * 
     * @param context
     *            Context对象
     * @return 设备的Mac地址
     */
    public static String getMacAddress(Context context) {
        String macAddress = "";
        try {
            WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifiMgr.getConnectionInfo();
            macAddress = info.getMacAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return macAddress;
    }
}
public class ScreenUtil {

    /**
     * 获取屏幕密度
     * 
     * @param context
     *            Context对象
     * @return 密度值
     */
    public static float getDensity(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float density = dm.density;
            return density;
        } catch (Throwable e) {
            e.printStackTrace();
            return 1.0f;
        }
    }

    /**
     * 获取屏幕的宽度(单位:像素)
     * 
     * @param context
     *            Context对象
     * @return 宽度值
     */
    public static int getScreenWidth(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            int screenWidth = dm.widthPixels;
            return screenWidth;
        } catch (Throwable e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取屏幕的高度(单位:像素)
     * 
     * @param context
     *            Context对象
     * @return 高度值
     */
    public static int getScreenHeight(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            int screenHeight = dm.heightPixels;
            return screenHeight;
        } catch (Throwable e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取屏幕分辨率
     * 
     * @param context
     *            Context对象
     * @return 分辨率
     */
    public static String getScreenSize(Context context) {

        return getScreenHeight(context) + "*" + getScreenWidth(context);
    }

    /**
     * dp转像素(px)
     * 
     * @param context
     *            Context对象
     * @param dp
     *            dp值
     * @return px值
     */
    public static float dpToPx(Context context, float dp) {
        if (context == null) {
            return -1;
        }
        return dp * context.getResources().getDisplayMetrics().density;
    }

    /**
     * 像素(px)转dp
     * 
     * @param context
     *            Context对象
     * @param px
     *            px值
     * @return dp值
     */
    public static float pxToDp(Context context, float px) {
        if (context == null) {
            return -1;
        }
        return px / context.getResources().getDisplayMetrics().density;
    }

    public static int dpToPxInt(Context context, float dp) {
        return (int) (dpToPx(context, dp) + 0.5f);
    }

    public static int pxToDpCeilInt(Context context, float px) {
        return (int) (pxToDp(context, px) + 0.5f);
    }
}
/**
     * 获取运营商
     * 
     * @param context
     *            Context对象
     * @return 运营商编识别码
     */
    public static String getProvidersName(Context context) {
        String providerName = "";
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String IMSI = telephonyManager.getSubscriberId();
            // IMSI号前面3位460是国家,紧接着后面2位 00 02是中国移动,01是中国联通,03是中国电信。
            if (TextUtils.isEmpty(IMSI))
                return providerName;
            if (IMSI.startsWith("46000"))
                // 中国移动
                providerName = "46000";
            else if (IMSI.startsWith("46002")) {
                // 中国移动
                providerName = "46002";
            } else if (IMSI.startsWith("46001"))
                // 中国联通
                providerName = "46001";
            else if (IMSI.startsWith("46003"))
                // 中国电信
                providerName = "46003";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return providerName;
    }

    /**
     * 获取手机号
     * 
     * @param context
     *            Context对象
     * @return 手机号
     */
    public static String getPhoneNumber(Context context) {
        String number = "";
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        number = tm.getLine1Number();
        return number == null ? "" : number.replace("+86", "");
    }

    /**
     * 获取SIM卡的ISO国家码
     * 
     * @param context
     *            Context对象
     * @return ISO国家码
     */
    public static String getCountry(Context context) {
        String number = "";
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        number = tm.getSimCountryIso();
        return number;
    }

 

posted @ 2019-05-09 17:48  JhonMr  阅读(248)  评论(0编辑  收藏  举报