Android 手機上獲取物理唯一標識碼

轉自:http://hi.baidu.com/weizi/item/f1d6671030e7e68d88a95638


唯一標識碼這東西在網絡應用中非常有用,例如檢測是否重複註冊之類的。

 

Java代碼  收藏代碼
  1. import android.provider.Settings.Secure;  
  2. private String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);  
  3.    
 

 

   我們在項目過程中或多或少會使用到設備的唯一識別碼,我們希望能夠得到一個穩定、可靠的設備唯一識別碼。今天我們將介紹幾種方式。

 

1. DEVICE_ID

 

 

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

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

 

2. MAC ADDRESS

 

我們也可以通過手機的Wifi或者藍牙設備獲取MAC ADDRESS作爲DEVICE ID,但是並不建議這麼做,因爲並不是所有的設備都有Wifi,並且,如果Wifi沒有打開,那硬件設備無法返回MAC ADDRESS.

 

3. Serial Number

在Android 2.3可以通過android.os.Build.SERIAL獲取,非手機設備可以通過該接口獲取。

 

4. ANDROID_ID

ANDROID_ID是設備第一次啓動時產生和存儲的64bit的一個數,當設備被wipe後該數重置

ANDROID_ID似乎是獲取Device ID的一個好選擇,但它也有缺陷:

 

  • 它在Android <=2.1 or Android >=2.3的版本是可靠、穩定的,但在2.2的版本並不是100%可靠的
  • 在主流廠商生產的設備上,有一個很經常的bug,就是每個設備都會產生相同的ANDROID_ID:9774d56d682e549c

 

5. Installtion ID : UUID

以上四種方式都有或多或少存在的一定的侷限性或者bug,在這裏,有另外一種方式解決,就是使用UUID,該方法無需訪問設備的資源,也跟設備類型無關。

這 種方式是通過在程序安裝後第一次運行後生成一個ID實現的,但該方式跟設備唯一標識不一樣,它會因爲不同的應用程序而產生不同的ID,而不是設備唯一 ID。因此經常用來標識在某個應用中的唯一ID(即Installtion ID),或者跟蹤應用的安裝數量。很幸運的,Google Developer Blog提供了這樣的一個框架:

 

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

 

總結:

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

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

 

Java代碼  收藏代碼
  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. public class DeviceUuidFactory {  
  8.     protected static final String PREFS_FILE = "device_id.xml";  
  9.     protected static final String PREFS_DEVICE_ID = "device_id";  
  10.     protected static UUID uuid;  
  11.   
  12.     public DeviceUuidFactory(Context context) {  
  13.         if( uuid ==null ) {  
  14.             synchronized (DeviceUuidFactory.class) {  
  15.                 if( uuid == null) {  
  16.                     final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);  
  17.                     final String id = prefs.getString(PREFS_DEVICE_ID, null );  
  18.                     if (id != null) {  
  19.                         // Use the ids previously computed and stored in the prefs file  
  20.                         uuid = UUID.fromString(id);  
  21.                     } else {  
  22.                         final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);  
  23.                         // Use the Android ID unless it's broken, in which case fallback on deviceId,  
  24.                         // unless it's not available, then fallback on a random number which we store  
  25.                         // to a prefs file  
  26.                         try {  
  27.                             if (!"9774d56d682e549c".equals(androidId)) {  
  28.                                 uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));  
  29.                             } else {  
  30.                                 final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();  
  31.                                 uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();  
  32.                             }  
  33.                         } catch (UnsupportedEncodingException e) {  
  34.                             throw new RuntimeException(e);  
  35.                         }  
  36.                         // Write the value out to the prefs file  
  37.                         prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();  
  38.                     }  
  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代碼  收藏代碼
  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支持


發佈了28 篇原創文章 · 獲贊 6 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章