获得ip、mac、uuid、手机硬件制造商、手机厂商、手机品牌、手机型号、系统版本号、手机IMEI、网络无线/4g/是否有网络、静默安装/卸载app、重启设备、当前包信息PackageInfo等等

public class SystemUtils {

    private static Context context = LemonConfig.getApplicationContext();

    /**
     * 获得IP地址,分为两种情况,一是wifi下,二是移动网络下,得到的ip地址是不一样的
     */
    public static String getIPAddress() {

        NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }
            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                //调用方法将int转换为地址字符串
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }
    //将得到的int类型的IP转换为String类型

    private static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * 获取机顶盒,电视有线还是无线:
     *      0:无网络连接
     *      1:有线网络
     *      2:无线网络
     *
     * @param context
     * @return
     */
    public static int getNetTypeTV(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = null;
        if (connectivityManager != null) {
            info = connectivityManager.getActiveNetworkInfo();
        }
        if (info == null) {
            return 0;
        }
        boolean iscon = info.isAvailable();
        if (!iscon) {
            return 0;
        }
        if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
            return 1;
        } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            return 2;
        } else {
            return 0;
        }
    }
    /**
     * 获取有线的mac地址
     * @return
     */
    public static String getLocalMacAddress() {
        String mac="";
        try {
            Enumeration localEnumeration=NetworkInterface.getNetworkInterfaces();

            while (localEnumeration.hasMoreElements()) {
                NetworkInterface localNetworkInterface=(NetworkInterface) localEnumeration.nextElement();
                String interfaceName=localNetworkInterface.getDisplayName();

                if (interfaceName==null) {
                    continue;
                }

                if (interfaceName.equals("eth0")) {
                    // MACAddr = convertMac(localNetworkInterface
                    // .getHardwareAddress());
                    mac=convertToMac(localNetworkInterface.getHardwareAddress());
                    if (mac!=null&&mac.startsWith("0:")) {
                        mac="0"+mac;
                    }
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return mac;
    }

    private static String convertToMac(byte[] mac) {
        StringBuilder sb=new StringBuilder();
        for (int i=0; i=0&&b<=16) {
                value=b;
                sb.append("0"+Integer.toHexString(value));
            } else if (b>16) {
                value=b;
                sb.append(Integer.toHexString(value));
            } else {
                value=256+b;
                sb.append(Integer.toHexString(value));
            }
            if (i!=mac.length-1) {
                sb.append(":");
            }
        }
        return sb.toString();
    }

    /**
     * 获取无线的mac地址
     * @return
     */
    public static String getWifiMacAddress(Context context) {
        String mac="";
        WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info=wifi.getConnectionInfo();
        if (null!=info) {
            mac=info.getMacAddress();
        }
        return mac;
    }
    /**
     * 根据网络不同,返回不同的mac地址
     * @return
     */
    public static String getMacAddress(){
        if (getNetTypeTV(context)==1) {
            return getLocalMacAddress();
        }else if (getNetTypeTV(context)==2){
            return getWifiMacAddress(context);
        }
        return "02:00:00:00:00:00";
    }

    /**
     * 获取手机IMEI(需要“android.permission.READ_PHONE_STATE”权限)
     *
     * @return 手机IMEI
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getIMEI() {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE);
        if (tm != null) {
            return tm.getDeviceId();
        }
        return null;
    }

    /**
     * 获取手机的IMSI号码
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getIMSI() {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE);
        if (tm != null) {
            return tm.getSubscriberId();
        }
        return null;
    }
    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如:当前设置的是“中文-中国”,则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机品牌
     *
     * @return 手机品牌
     */
    public static String getDeviceName() {
        return android.os.Build.BRAND;
    }
    /**
     * 获取手机硬件制造商
     *
     * @return 手机硬件制造商
     */
    public static String getMakeName() {
        return android.os.Build.MANUFACTURER;
    }
    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getFactoryName() {
        return android.os.Build.PRODUCT;
    }
    /**
     * 得到全局唯一UUID
     */
    public String getUUID(){
        String uuid=SPUtils.getInstance().getString(SpKeys.UUID);
        if(TextUtils.isEmpty(uuid)){
            uuid = UUID.randomUUID().toString();
            SPUtils.getInstance().put(SpKeys.UUID,uuid);
        }
        return uuid;
    }
    /**
     * 重启设备
     */
    public static void rebootSystem() {
        PowerManager manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        manager.reboot("重新启动系统");
    }

    /**
     * 检查当前网络是否可用
     *
     * @param
     * @return
     */

    public static boolean isNetwork() {
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
//                    System.out.println(i + "===状态===" + networkInfo[i].getState());
//                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    /***
     * packageInfo.versionName
     * packageInfo.versionCode
     */
    //获得包信息
    public static PackageInfo getPackageInfo(){
        //获取packageManager实例
        PackageManager packageManager = context.getPackageManager();
        // 获取包名
        String packageName = context.getPackageName();
        int flag = 0;
        PackageInfo packageInfo = null;

        // 获取packageInfo
        try {
            packageInfo = packageManager.getPackageInfo(packageName, flag);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo;
    }
    /**
     * @param packageName 应用包名
     */
    public static void uninstallPackage(String packageName) {
        Intent intent = new Intent(context, context.getClass());
        PendingIntent sender = PendingIntent.getActivity(context, 0, intent, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            PackageInstaller mPackageInstaller = context.getPackageManager().getPackageInstaller();
            mPackageInstaller.uninstall(packageName, sender.getIntentSender());
        }
    }
    /**
     * @param filepathApk 文件路径
     */
    public static void installPackage(String filepathApk) {
        try {
            PackageInstaller pi = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                pi = context.getPackageManager().getPackageInstaller();
            }
            //给定模式,创建新的参数,创建新安装会话,返回唯一 Id
            int sessionId= 0;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                sessionId = pi.createSession(new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL));
            }
            //打开现有会话,主动执行工作
            PackageInstaller.Session session = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                session = pi.openSession(sessionId);
            }
            long sizeBytes = 0;
            final File file = new File(filepathApk);
            if (file.isFile()) {
                sizeBytes = file.length();
            }
            InputStream in = null;
            OutputStream out = null;
            in = new FileInputStream(filepathApk);
            //打开一个流,将一个APK文件写入会话
            //指定有效长度系统将预先分配底层磁盘空间以优化磁盘上的放置
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                out = session.openWrite("app_store_session", 0, sizeBytes);
            }
            int total = 0;
            byte[] buffer = new byte[65536];
            int len;
            while ((len= in.read(buffer)) != -1) {
                total += len;
                out.write(buffer, 0, len);
            }
            //根据需要调用,用来确保字节已保留到磁盘
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                session.fsync(out);
            }
            in.close();
            out.close();
            LogUtils.d("Success: streamed apk " + total + " bytes");
            PendingIntent broadCastTest = PendingIntent.getBroadcast(context, sessionId, new Intent("action.install.success"), PendingIntent.FLAG_UPDATE_CURRENT);
            //提交之前必须关闭所有流
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                session.commit(broadCastTest.getIntentSender());
            }
            session.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

你可能感兴趣的:(android系统)