美文网首页
AndroidUtil 手机信息工具类

AndroidUtil 手机信息工具类

作者: 颤抖的闪电 | 来源:发表于2017-10-24 14:21 被阅读0次

    前言:据项目需求,整理了一个AndroidUtil工具类,可获取手机信息 & MAC地址 & 开机时间 & ip地址 &手机的imei、imsi等号码。

    /**
     * @desc 手机信息 & MAC地址 & 开机时间 & ip地址 &手机的imei、imsi等号码
     * @auth 方毅超
     * @time 2017/10/24 11:27
     */
    
    public class AndroidUtil {
        /**
         * MAC地址
         *
         * @return
         */
        public static String getMacAddress() {
     /*获取mac地址有一点需要注意的就是android 6.0版本后,以下注释方法不再适用,
     不管任何手机都会返回"02:00:00:00:00:00"这个默认的mac地址,
     这是googel官方为了加强权限管理而禁用了getSYstemService(Context.WIFI_SERVICE)方法来获得mac地址。*/
            //        String macAddress= "";
    //        WifiManager wifiManager = (WifiManager) MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
    //        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    //        macAddress = wifiInfo.getMacAddress();
    //        return macAddress;
    
            String macAddress = null;
            StringBuffer buf = new StringBuffer();
            NetworkInterface networkInterface = null;
            try {
                networkInterface = NetworkInterface.getByName("eth1");
                if (networkInterface == null) {
                    networkInterface = NetworkInterface.getByName("wlan0");
                }
                if (networkInterface == null) {
                    return "02:00:00:00:00:02";
                }
                byte[] addr = networkInterface.getHardwareAddress();
                for (byte b : addr) {
                    buf.append(String.format("%02X:", b));
                }
                if (buf.length() > 0) {
                    buf.deleteCharAt(buf.length() - 1);
                }
                macAddress = buf.toString();
            } catch (SocketException e) {
                e.printStackTrace();
                return "02:00:00:00:00:02";
            }
            return macAddress;
        }
    
        /**
         * 获得IP地址,分为两种情况,一是wifi下,二是移动网络下,得到的ip地址是不一样的
         * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
         */
        public static String getIPAddress(Context context) {
            NetworkInfo info = ((ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                    try {
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> 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类型
         *
         * @param ip
         * @return
         */
        private static String intIP2StringIP(int ip) {
            return (ip & 0xFF) + "." +
                    ((ip >> 8) & 0xFF) + "." +
                    ((ip >> 16) & 0xFF) + "." +
                    (ip >> 24 & 0xFF);
        }
    
        /**
         * 获取 ANDROID_ID
         */
        public static String getAndroidId(Context context) {
            String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            return androidId;
        }
    
        /**
         * 获取 开机时间
         */
        public static String getBootTimeString() {
            long ut = SystemClock.elapsedRealtime() / 1000;
            int h = (int) ((ut / 3600));
            int m = (int) ((ut / 60) % 60);
            return h + ":" + m;
        }
    
        /**
         * 手机信息
         * 需要 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
         *
         * @return
         */
        public static String printSystemInfo() {
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = dateFormat.format(date);
            StringBuilder sb = new StringBuilder();
            sb.append("_______  系统信息  ").append(time).append(" ______________");
            sb.append("\nID                 :").append(Build.ID); // Either  a changelist number, or a label like "M4-rc20".
            sb.append("\nBRAND              :").append(Build.BRAND); //品牌名 如 Xiaomi
            sb.append("\nMODEL              :").append(Build.MODEL); //手机型号
            sb.append("\nRELEASE            :").append(Build.VERSION.RELEASE); //frimware版本(系统版本) 如:2.1-update1
            sb.append("\nSDK                :").append(Build.VERSION.SDK); //sdk版本号
    
            sb.append("\n_______ OTHER _______");
            sb.append("\nBOARD              :").append(Build.BOARD); //基板名 如 MSM8974
            sb.append("\nPRODUCT            :").append(Build.PRODUCT); //The name of the overall product.
            sb.append("\nDEVICE             :").append(Build.DEVICE); //品牌型号名,如小米4对应cancro
            sb.append("\nFINGERPRINT        :").append(Build.FINGERPRINT); //包含制造商,设备名,系统版本等诸多信息 如  Xiaomi/cancro_wc_lte/cancro:6.0.1/MMB29M/V8.1.3.0.MXDCNDI:user/release-keys
            sb.append("\nHOST               :").append(Build.HOST); // 如 c3-miui-ota-bd43
            sb.append("\nTAGS               :").append(Build.TAGS); //Comma-separated tags describing the build, like "unsigned,debug".
            sb.append("\nTYPE               :").append(Build.TYPE); //The type of build, like "user" or "eng".
            sb.append("\nTIME               :").append(Build.TIME); //当前时间,毫秒值
            sb.append("\nINCREMENTAL        :").append(Build.VERSION.INCREMENTAL);
    
            sb.append("\n_______ CUPCAKE-3 _______");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                sb.append("\nDISPLAY            :").append(Build.DISPLAY); // 如 MMB29M
            }
    
            sb.append("\n_______ DONUT-4 _______");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
                sb.append("\nSDK_INT            :").append(Build.VERSION.SDK_INT);
                sb.append("\nMANUFACTURER       :").append(Build.MANUFACTURER); // The manufacturer of the product/hardware. 如 Xiaomi
                sb.append("\nBOOTLOADER         :").append(Build.BOOTLOADER); //The system bootloader version number. 如
                sb.append("\nCPU_ABI            :").append(Build.CPU_ABI); // 如 armeabi-v7a
                sb.append("\nCPU_ABI2           :").append(Build.CPU_ABI2); // 如 armeabi
                sb.append("\nHARDWARE           :").append(Build.HARDWARE); // The name of the hardware (from the kernel command line or /proc). 如 qcom
                sb.append("\nUNKNOWN            :").append(Build.UNKNOWN); // Value used for when a build property is unknown.
                sb.append("\nCODENAME           :").append(Build.VERSION.CODENAME);
            }
    
            sb.append("\n_______ GINGERBREAD-9 _______");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                sb.append("\nSERIAL             :").append(Build.SERIAL); // A hardware serial number, if available. 如 abcdefgh
            }
            return sb.toString();
        }
    
        /**
         * 获取手机的IMEI号码
         * 使用TelephonyManager时需要 <uses-permission android:name="READ_PHONE_STATE" />
         */
        public static String getPhoneIMEI(Context context) {
            TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = mTm.getDeviceId();
            return imei;
        }
        /**
         * 获取手机的imsi号码
         * 使用TelephonyManager时需要 <uses-permission android:name="READ_PHONE_STATE" />
         */
        public static String getPhoneIMSI(Context context) {
            TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imsi = mTm.getSubscriberId();
            return imsi;
        }
        /**
         * 获取手机号码
         * 使用TelephonyManager时需要 <uses-permission android:name="READ_PHONE_STATE" />
         */
        public static String getPhoneNumer(Context context) {
            TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String numer = mTm.getLine1Number(); // 手机号码,有的可得,有的不可得
            return numer;
        }
        
    }
    
    
        
       //# [Android下获取设备唯一标识(UDID, DeviceID...)](https://www.cnblogs.com/Nbox1989/p/4346347.html)
    
        protected static final String PREFS_FILE = "qy_gank_device_id.xml";
        protected static final String PREFS_DEVICE_ID = "qy_gank_device_id";
        protected static String uuid;
    
        static public String getUDID(Context s_instance) {
            if (uuid == null) {
                synchronized (PhoneUtils.class) {
                    if (uuid == null) {
                        final SharedPreferences prefs = s_instance.getSharedPreferences(PREFS_FILE, 0);
                        final String id = prefs.getString(PREFS_DEVICE_ID, null);
    
                        if (id != null) {
                            // Use the ids previously computed and stored in the prefs file
                            uuid = id;
                        } else {
    
                            final String androidId = Settings.Secure.getString(s_instance.getContentResolver(), Settings.Secure.ANDROID_ID);
    
                            // Use the Android ID unless it's broken, in which case fallback on deviceId,
                            // unless it's not available, then fallback on a random number which we store
                            // to a prefs file
                            try {
                                if (!"9774d56d682e549c".equals(androidId)) {
                                    uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
                                } else {
                                    final String deviceId = ((TelephonyManager) s_instance.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                                    uuid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")).toString() : UUID.randomUUID().toString();
                                }
                            } catch (UnsupportedEncodingException e) {
                                throw new RuntimeException(e);
                            }
    
                            // Write the value out to the prefs file
                            prefs.edit().putString(PREFS_DEVICE_ID, uuid).commit();
                        }
                    }
                }
            }
            return uuid;
        }
    

    后记:2017-10-30,将代码稍作了整理。
    感谢:
    Android 获得设备状态信息、Mac地址、IP地址
    Android编程获取手机型号,本机电话号码,sdk版本号及firmware版本号号(即系统版本号号)

    相关文章

      网友评论

          本文标题:AndroidUtil 手机信息工具类

          本文链接:https://www.haomeiwen.com/subject/npntpxtx.html