【轉】 android獲取設備唯一標識完美解決方案


[java]  view plain  copy
 
 print?
  1. <p style="margin: 10px auto; padding-top: 0px; padding-bottom: 0px; color: rgb(51, 51, 51); font-family: verdana, Arial, Helvetica, sans-serif; font-size: 14px; line-height: 25.2px;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"> /**</span></p>  * deviceID的組成為:渠道標志+識別符來源標志+hash后的終端識別符 
  2.   * 
  3.   * 渠道標志為: 
  4.   * 1,andriod(a) 
  5.   * 
  6.   * 識別符來源標志: 
  7.   * 1, wifi mac地址(wifi); 
  8.   * 2, IMEI(imei); 
  9.   * 3, 序列號(sn); 
  10.   * 4, id:隨機碼。若前面的都取不到時,則隨機生成一個隨機碼,需要緩存。 
  11.   * 
  12.   * @param context 
  13.   * @return 
  14.   */  
  15. public static String getDeviceId(Context context) {  
  16.   StringBuilder deviceId = new StringBuilder();  
  17.   // 渠道標志  
  18.   deviceId.append("a");  
  19.   try {  
  20.     //wifi mac地址  
  21.     WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
  22.     WifiInfo info = wifi.getConnectionInfo();  
  23.     String wifiMac = info.getMacAddress();  
  24.     if(!isEmpty(wifiMac)){  
  25.       deviceId.append("wifi");  
  26.       deviceId.append(wifiMac);  
  27.       PALog.e("getDeviceId : ", deviceId.toString());  
  28.       return deviceId.toString();  
  29.     }  
  30.     //IMEI(imei)  
  31.     TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);  
  32.     String imei = tm.getDeviceId();  
  33.     if(!isEmpty(imei)){  
  34.       deviceId.append("imei");  
  35.       deviceId.append(imei);  
  36.       PALog.e("getDeviceId : ", deviceId.toString());  
  37.       return deviceId.toString();  
  38.     }  
  39.     //序列號(sn)  
  40.     String sn = tm.getSimSerialNumber();  
  41.     if(!isEmpty(sn)){  
  42.       deviceId.append("sn");  
  43.       deviceId.append(sn);  
  44.       PALog.e("getDeviceId : ", deviceId.toString());  
  45.       return deviceId.toString();  
  46.     }  
  47.     //如果上面都沒有, 則生成一個id:隨機碼  
  48.     String uuid = getUUID(context);  
  49.     if(!isEmpty(uuid)){  
  50.       deviceId.append("id");  
  51.       deviceId.append(uuid);  
  52.       PALog.e("getDeviceId : ", deviceId.toString());  
  53.       return deviceId.toString();  
  54.     }  
  55.   } catch (Exception e) {  
  56.     e.printStackTrace();  
  57.     deviceId.append("id").append(getUUID(context));  
  58.   }  
  59.   PALog.e("getDeviceId : ", deviceId.toString());  
  60.   return deviceId.toString();  
  61. }  
  62. /** 
  63.  * 得到全局唯一UUID 
  64.  */  
  65. public static String getUUID(Context context){  
  66.   SharedPreferences mShare = getSysShare(context, "sysCacheMap");  
  67.   if(mShare != null){  
  68.     uuid = mShare.getString("uuid", "");  
  69.   }  
  70.   if(isEmpty(uuid)){  
  71.     uuid = UUID.randomUUID().toString();  
  72.     saveSysMap(context, "sysCacheMap", "uuid", uuid);  
  73.   }  
  74.   PALog.e(tag, "getUUID : " + uuid);  
  75. return uuid;  
  76. }  

有時需要對用戶設備進行標識,所以希望能夠得到一個穩定可靠並且唯一的識別碼。雖然Android系統中提供了這樣設備識別碼,但是由於Android系統版本、廠商定制系統中的Bug等限制,穩定性和唯一性並不理想。而通過其他硬件信息標識也因為系統版本、手機硬件等限制存在不同程度的問題。

下面收集了一些“有能力”或“有一定能力”作為設備標識的串碼。

DEVICE_ID

這是Android系統為開發者提供的用於標識手機設備的串號,也是各種方法中普適性較高的,可以說幾乎所有的設備都可以返回這個串號,並且唯一性良好。

這個DEVICE_ID可以同通過下面的方法獲取:

 

[java]  view plain  copy
 
 print?
  1. TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);  
  2. String DEVICE_ID = tm.getDeviceId();   

 

假設我們確實需要用到真實設備的標識,可能就需要用到DEVICE_ID。在以前,我們的Android設備是手機,這個DEVICE_ID可以同通過TelephonyManager.getDeviceId()獲取,它根據不同的手機設備返回IMEI,MEID或者ESN碼,但它在使用的過程中會遇到很多問題:

  • 非手機設備: 如果只帶有Wifi的設備或者音樂播放器沒有通話的硬件功能的話就沒有這個DEVICE_ID
  • 權限: 獲取DEVICE_ID需要READ_PHONE_STATE權限,但如果我們只為了獲取它,沒有用到其他的通話功能,那這個權限有點大才小用
  • bug:在少數的一些手機設備上,該實現有漏洞,會返回垃圾,如:zeros或者asterisks的產品

MAC ADDRESS

可以使用手機Wifi或藍牙的MAC地址作為設備標識,但是並不推薦這么做,原因有以下兩點:

  • 硬件限制:並不是所有的設備都有Wifi和藍牙硬件,硬件不存在自然也就得不到這一信息。
  • 獲取的限制:如果Wifi沒有打開過,是無法獲取其Mac地址的;而藍牙是只有在打開的時候才能獲取到其Mac地址。

獲取Wifi Mac地址:

獲取藍牙 Mac地址:

Sim Serial Number

裝有SIM卡的Android 2.3設備,可以通過下面的方法獲取到Sim Serial Number:

 

[java]  view plain  copy
 
 print?
  1. TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);   
  2. String SimSerialNumber = tm.getSimSerialNumber();   

 

注意:對於CDMA設備,返回的是一個空值!

ANDROID_ID

在設備首次啟動時,系統會隨機生成一個64位的數字,並把這個數字以16進制字符串的形式保存下來,這個16進制的字符串就是ANDROID_ID,當設備被wipe后該值會被重置。可以通過下面的方法獲取:

 

[java]  view plain  copy
 
 print?
  1. import android.provider.Settings;  
  2. String ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);  
ANDROID_ID可以作為設備標識,但需要注意:

 

  • 廠商定制系統的Bug:不同的設備可能會產生相同的ANDROID_ID:9774d56d682e549c。
  • 廠商定制系統的Bug:有些設備返回的值為null。
  • 設備差異:對於CDMA設備,ANDROID_ID和TelephonyManager.getDeviceId() 返回相同的值。
  • 它在Android <=2.1 or Android >=2.3的版本是可靠、穩定的,但在2.2的版本並不是100%可靠的

Serial Number

Android系統2.3版本以上可以通過下面的方法得到Serial Number,且非手機設備也可以通過該接口獲取。

[java]  view plain  copy
 
 print?
  1. String SerialNumber = android.os.Build.SERIAL;   

以上幾種方式都或多或少存在一定的局限性或者Bug,如果並不是確實需要對硬件本身進行綁定,使用自己生成的UUID也是一個不錯的選擇,因為該方法無需訪問設備的資源,也跟設備類型無關。

 

Installtion ID

 

這種方式的原理是在程序安裝后第一次運行時生成一個ID,該方式和設備唯一標識不一樣,不同的應用程序會產生不同的ID,同一個程序重新安裝也會不同。所以這不是設備的唯一ID,但是可以保證每個用戶的ID是不同的。可以說是用來標識每一份應用程序的唯一ID(即Installtion ID),可以用來跟蹤應用的安裝數量等。

Google Developer Blog提供了這樣的一個框架:

[java]  view plain  copy
 
 print?
  1. public class Installation {  
  2.     private static String sID = null;  
  3.     private static final String INSTALLATION = "INSTALLATION";  
  4.   
  5.     public synchronized static String id(Context context) {  
  6.         if (sID == null) {    
  7.             File installation = new File(context.getFilesDir(), INSTALLATION);  
  8.             try {  
  9.                 if (!installation.exists())  
  10.                     writeInstallationFile(installation);  
  11.                 sID = readInstallationFile(installation);  
  12.             } catch (Exception e) {  
  13.                 throw new RuntimeException(e);  
  14.             }  
  15.         }  
  16.         return sID;  
  17.     }  
  18.   
  19.     private static String readInstallationFile(File installation) throws IOException {  
  20.         RandomAccessFile f = new RandomAccessFile(installation, "r");  
  21.         byte[] bytes = new byte[(int) f.length()];  
  22.         f.readFully(bytes);  
  23.         f.close();  
  24.         return new String(bytes);  
  25.     }  
  26.   
  27.     private static void writeInstallationFile(File installation) throws IOException {  
  28.         FileOutputStream out = new FileOutputStream(installation);  
  29.         String id = UUID.randomUUID().toString();  
  30.         out.write(id.getBytes());  
  31.         out.close();  
  32.     }  
  33. }  

設備唯一ID

上文可以看出,Android系統中並沒有可以可靠獲取所有廠商設備唯一ID的方法,各個方法都有自己的使用范圍和局限性,這也是目前流行的Android系統版本過多,設備也是來自不同廠商,且沒有統一標准等原因造成的。

從目前發展來看,Android系統多版本共存還會持續較長的時間,而Android系統也不會被某個設備生產廠商壟斷,長遠看Android基礎系統將會趨於穩定,設備標識也將會作為系統基礎部分而標准化,屆時這一問題才有望徹底解決。

目前的解決辦法,比較可行的是一一適配,在保證大多數設備方便的前提下,如果獲取不到,使用其他備選信息作為標識,即自己再封裝一個設備ID出來,通過內部算法保證盡量和設備硬件信息相關,以及標識的唯一性。

總結

綜合以上所述,為了實現在設備上更通用的獲取設備唯一標識,我們可以實現這樣的一個類,為每個設備產生唯一的UUID,以ANDROID_ID為基礎,在獲取失敗時以TelephonyManager.getDeviceId()為備選方法,如果再失敗,使用UUID的生成策略。

重申下,以下方法是生成Device ID,在大多數情況下Installtion ID能夠滿足我們的需求,但是如果確實需要用到Device ID,那可以通過以下方式實現:

[java]  view plain  copy
 
 print?
  1. import android.content.Context;  
  2. import android.content.SharedPreferences;  
  3. import android.provider.Settings.Secure;  
  4. import android.telephony.TelephonyManager;  
  5. import java.io.UnsupportedEncodingException;  
  6. import java.util.UUID;  
  7.   
  8. public class DeviceUuidFactory {  
  9.     protected static final String PREFS_FILE = "device_id.xml";  
  10.     protected static final String PREFS_DEVICE_ID = "device_id";  
  11.     protected static UUID uuid;  
  12.   
  13.     public DeviceUuidFactory(Context context) {  
  14.         if( uuid ==null ) {  
  15.             synchronized (DeviceUuidFactory.class) {  
  16.                 if( uuid == null) {  
  17.                     final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);  
  18.                     final String id = prefs.getString(PREFS_DEVICE_ID, null );  
  19.                     if (id != null) {  
  20.                         // Use the ids previously computed and stored in the prefs file  
  21.                         uuid = UUID.fromString(id);  
  22.                     } else {  
  23.                         final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);  
  24.                         // Use the Android ID unless it's broken, in which case fallback on deviceId,  
  25.                         // unless it's not available, then fallback on a random number which we store  
  26.                         // to a prefs file  
  27.                         try {  
  28.                             if (!"9774d56d682e549c".equals(androidId)) {  
  29.                                 uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));  
  30.                             } else {  
  31.                                 final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();  
  32.                                 uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();  
  33.                             }  
  34.                         } catch (UnsupportedEncodingException e) {  
  35.                             throw new RuntimeException(e);  
  36.                         }  
  37.                         // Write the value out to the prefs file  
  38.                         prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();  
  39.                     }  
  40.                 }  
  41.             }  
  42.         }  
  43.     }  
  44.     /** 
  45.      * Returns a unique UUID for the current android device.  As with all UUIDs, this unique ID is "very highly likely" 
  46.      * to be unique across all Android devices.  Much more so than ANDROID_ID is. 
  47.      * 
  48.      * The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on 
  49.      * TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back 
  50.      * on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a 
  51.      * usable value. 
  52.      * 
  53.      * In some rare circumstances, this ID may change.  In particular, if the device is factory reset a new device ID 
  54.      * may be generated.  In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2 
  55.      * to a newer, non-buggy version of Android, the device ID may change.  Or, if a user uninstalls your app on 
  56.      * a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation. 
  57.      * 
  58.      * Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT 
  59.      * change after a factory reset.  Something to be aware of. 
  60.      * 
  61.      * Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly. 
  62.      * 
  63.      * @see http://code.google.com/p/android/issues/detail?id=10603 
  64.      * 
  65.      * @return a UUID that may be used to uniquely identify your device for most purposes. 
  66.      */  
  67.     public UUID getDeviceUuid() {  
  68.         return uuid;  
  69.     }  
  70. }  
如何獲取Android手機的唯一標識?

代碼: 這里是你在Android里讀出 唯一的 IMSI-ID / IMEI-ID 的方法。

Java: 

 

[java]  view plain  copy
 
 print?
  1. String myIMSI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);   
  2. // within my emulator it returns: 310995000000000   
  3.   
  4. String myIMEI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMEI);   
  5. // within my emulator it returns: 000000000000000   
注:android.os.SystemProperties的標簽被打上@hide了,所以sdk中並不會存在。如果需要使用,需要有android的source code支持。
 
from:http://blog.csdn.net/aa1733519509/article/details/50053553


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM