AndroidUtil 휴대폰 정보 도구 클래스

11752 단어
선언: 프로젝트 수요에 따라 안드로이드 Util 도구류를 정리하여 핸드폰 정보 & 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       
     * 
     */
    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 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  
     *
     * @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;
    }

    /**
     *     
     *    
     *
     * @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("
ID :").append(Build.ID); // Either a changelist number, or a label like "M4-rc20". sb.append("
BRAND :").append(Build.BRAND); // Xiaomi sb.append("
MODEL :").append(Build.MODEL); // sb.append("
RELEASE :").append(Build.VERSION.RELEASE); //frimware ( ) :2.1-update1 sb.append("
SDK :").append(Build.VERSION.SDK); //sdk sb.append("
_______ OTHER _______"); sb.append("
BOARD :").append(Build.BOARD); // MSM8974 sb.append("
PRODUCT :").append(Build.PRODUCT); //The name of the overall product. sb.append("
DEVICE :").append(Build.DEVICE); // , 4 cancro sb.append("
FINGERPRINT :").append(Build.FINGERPRINT); // , , Xiaomi/cancro_wc_lte/cancro:6.0.1/MMB29M/V8.1.3.0.MXDCNDI:user/release-keys sb.append("
HOST :").append(Build.HOST); // c3-miui-ota-bd43 sb.append("
TAGS :").append(Build.TAGS); //Comma-separated tags describing the build, like "unsigned,debug". sb.append("
TYPE :").append(Build.TYPE); //The type of build, like "user" or "eng". sb.append("
TIME :").append(Build.TIME); // , sb.append("
INCREMENTAL :").append(Build.VERSION.INCREMENTAL); sb.append("
_______ CUPCAKE-3 _______"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) { sb.append("
DISPLAY :").append(Build.DISPLAY); // MMB29M } sb.append("
_______ DONUT-4 _______"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { sb.append("
SDK_INT :").append(Build.VERSION.SDK_INT); sb.append("
MANUFACTURER :").append(Build.MANUFACTURER); // The manufacturer of the product/hardware. Xiaomi sb.append("
BOOTLOADER :").append(Build.BOOTLOADER); //The system bootloader version number. sb.append("
CPU_ABI :").append(Build.CPU_ABI); // armeabi-v7a sb.append("
CPU_ABI2 :").append(Build.CPU_ABI2); // armeabi sb.append("
HARDWARE :").append(Build.HARDWARE); // The name of the hardware (from the kernel command line or /proc). qcom sb.append("
UNKNOWN :").append(Build.UNKNOWN); // Value used for when a build property is unknown. sb.append("
CODENAME :").append(Build.VERSION.CODENAME); } sb.append("
_______ GINGERBREAD-9 _______"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { sb.append("
SERIAL :").append(Build.SERIAL); // A hardware serial number, if available. abcdefgh } return sb.toString(); } /** * IMEI * TelephonyManager */ public static String getPhoneIMEI(Context context) { TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imei = mTm.getDeviceId(); return imei; } /** * imsi * TelephonyManager */ public static String getPhoneIMSI(Context context) { TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imsi = mTm.getSubscriberId(); return imsi; } /** * * TelephonyManager */ 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, 코드를 약간 정리했습니다.감사:안드로이드는 장치 상태 정보,Mac주소,IP주소 안드로이드 프로그래밍은 핸드폰 모델,본기 전화번호,sdk버전 번호 및firmware버전 번호(즉 시스템 버전 번호)를 획득합니다.

좋은 웹페이지 즐겨찾기