1. 程式人生 > >Android裝置唯一標識小記

Android裝置唯一標識小記

許可權:

 <uses-permission android:name="android.permission.READ_PHONE_STATE" />

測試裝置:
小米pad2,HTCd816t(有卡),華為4c(無卡),vivo X6L(無卡)

1.IMEI
IMEI(International Mobile Equipment Identity,移動裝置國際識別碼,又稱為國際移動裝置標識)是手機的唯一識別號碼。

IMEI針對手機(有沒有手機卡都能獲取),pad上不適用,親測小米pad返回null
(根據通訊制式不同,可能是IMEI,MEID,ESN)
程式碼:

/**
    Returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones. Return null if device ID is not available.
 */
private String getIMEI() {
        TelephonyManager telephonyManager = (TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE);
        String IMEI = telephonyManager.getDeviceId();
        return
IMEI; }

2.ANDROID_ID
16進位制的64位字元,恢復出廠設定時,此值可能改變(官方文件有註釋,如下)
獲取方式:

/**
   A 64-bit number (as a hex string) that is randomly
   generated when the user first sets up the device and should remain
   constant for the lifetime of the user's device. The value may
   change if a factory reset is
performed on the device. */ private String getAndroidId(){ return Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID); }

3.IMSI
國際移動使用者識別碼(IMSI:International Mobile Subscriber Identification Number)是區別移動使用者的標誌
沒有手機卡返回null
手機卡手機通訊的唯一標識
獲取方法:

private String getIMSI() {
        TelephonyManager telephonyManager = (TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE);
        String IMSI = telephonyManager.getSubscriberId();
        return IMSI;
    }

4.序列號
android手機和pad都可以獲取

String SerialNumber = android.os.Build.SERIAL;
或者
public String getSerialNum() {
        try {
            Class localClass = Class.forName("android.os.SystemProperties");
            String str = (String) localClass.getMethod("get", new Class[]{String.class, String.class}).invoke(localClass, new Object[]{"ro.serialno", "unknown"});
            return str;
        } catch (Exception localException) {
        }
        return null;
    }

5.MAC地址
不建議作為唯一標示
有些手機不root進入手機工程模式可以臨時修改mac地址的值,重啟之後可以恢復正常,親測vivo X6L手機可以修改.
獲取方法:

 private String getMac() {
        String macSerial = null;
        String str = "";

        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 賦予預設值
            ex.printStackTrace();
        }
        return macSerial;
    }

總結:
可以使用1,4作為android裝置的唯一標識,也可以結合兩種值組合生成唯一標識。