獲取Android設備唯一標識碼

鏈接地址:http://www.cnblogs.com/lvcha/p/3721091.html

DEVICE_ID:

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

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

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);StringDEVICE_ID = tm.getDeviceId();

它會根據(jù)不同的手機設備返回IMEI,MEID或者ESN碼,但在使用的過程中有以下問題:

非手機設備:最開始搭載Android系統(tǒng)都手機設備,而現(xiàn)在也出現(xiàn)了非手機設備:如平板電腦、電子書、電視、音樂播放器等。這些設備沒有通話的硬件功能,系統(tǒng)中也就沒有TELEPHONY_SERVICE,自然也就無法通過上面的方法獲得DEVICE_ID。

權限問題:獲取DEVICE_ID需要READ_PHONE_STATE權限,如果只是為了獲取DEVICE_ID而沒有用到其他的通話功能,申請這個權限一來大才小用,二來部分用戶會懷疑軟件的安全性。

廠商定制系統(tǒng)中的Bug:少數(shù)手機設備上,由于該實現(xiàn)有漏洞,會返回垃圾,如:zeros或者asterisks

MAC ADDRESS

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

硬件限制:并不是所有的設備都有Wifi和藍牙硬件,硬件不存在自然也就得不到這一信息。

獲取的限制:如果Wifi沒有打開過,是無法獲取其Mac地址的;而藍牙是只有在打開的時候才能獲取到其Mac地址。

獲取Wifi Mac地址:

獲取藍牙 Mac地址:

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

Sim Serial Number

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

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);StringSimSerialNumber = tm.getSimSerialNumber();

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

ANDROID_ID

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

import android.provider.Settings;StringANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);

ANDROID_ID可以作為設備標識,但需要注意:

廠商定制系統(tǒng)的Bug:不同的設備可能會產(chǎn)生相同的ANDROID_ID:9774d56d682e549c。

廠商定制系統(tǒng)的Bug:有些設備返回的值為null。

設備差異:對于CDMA設備,ANDROID_ID和TelephonyManager.getDeviceId() 返回相同的值。

ANDROID_ID是設備第一次啟動時產(chǎn)生和存儲的64bit的一個數(shù),當設備被wipe后該數(shù)重置

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

它在Android <=2.1 or Android >=2.3的版本是可靠、穩(wěn)定的,但在2.2的版本并不是100%可靠的

在主流廠商生產(chǎn)的設備上,有一個很經(jīng)常的bug,就是每個設備都會產(chǎn)生相同的ANDROID_ID:9774d56d682e549c

Serial Number

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

StringSerialNumber = android.os.Build.SERIAL;

Installtion ID

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

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

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

public class Installation {

private static String sID = null;

private static final String INSTALLATION = "INSTALLATION";

public synchronized static String id(Context context) {

if (sID == null) {

File installation = new File(context.getFilesDir(), INSTALLATION);

try {

if (!installation.exists())

writeInstallationFile(installation);

sID = readInstallationFile(installation);

} catch (Exception e) {

throw new RuntimeException(e);

}

}

return sID;

}

private static String readInstallationFile(File installation) throws IOException {

RandomAccessFile f = new RandomAccessFile(installation, "r");

byte[] bytes = new byte[(int) f.length()];

f.readFully(bytes);

f.close();

return new String(bytes);

}

private static void writeInstallationFile(File installation) throws IOException {

FileOutputStream out = new FileOutputStream(installation);

String id = UUID.randomUUID().toString();

out.write(id.getBytes());

out.close();

}

}

設備唯一ID

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

從目前發(fā)展來看,Android系統(tǒng)多版本共存還會持續(xù)較長的時間,而Android系統(tǒng)也不會被某個設備生產(chǎn)廠商壟斷,長遠看Android基礎系統(tǒng)將會趨于穩(wěn)定,設備標識也將會作為系統(tǒng)基礎部分而標準化,屆時這一問題才有望徹底解決。

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

總結

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

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

packagecom.example.androidmac;

importandroid.content.Context;

importandroid.content.SharedPreferences;

importandroid.provider.Settings.Secure;

importandroid.telephony.TelephonyManager;

importjava.io.UnsupportedEncodingException;

importjava.util.UUID;

publicclassDeviceUuidFactory {

protectedstaticfinalStringPREFS_FILE="device_id.xml";

protectedstaticfinalStringPREFS_DEVICE_ID="device_id";

protectedstaticUUIDuuid;

publicDeviceUuidFactory(Context context) {

if(uuid==null) {

synchronized(DeviceUuidFactory.class) {

if(uuid==null) {

finalSharedPreferences prefs = context.getSharedPreferences(PREFS_FILE, 0);

finalString id = prefs.getString(PREFS_DEVICE_ID,null);

if(id !=null) {

// Use theidspreviously computed and stored in theprefsfile

uuid= UUID.fromString(id);

}else{

finalString androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

// Use the Android ID unless it's broken, in which casefallbackon deviceId,

// unless it's not available, thenfallbackon a random number which we store

// to aprefsfile

try{

if(!"9774d56d682e549c".equals(androidId)) {

uuid= UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));

}else{

finalString deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE)).getDeviceId();

uuid= deviceId!=null? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();

}

}catch(UnsupportedEncodingException e) {

thrownewRuntimeException(e);

}

// Write the value out to theprefsfile

prefs.edit().putString(PREFS_DEVICE_ID,uuid.toString() ).commit();

}

}

}

}

}

/**

* Returns a unique UUID for the current android device.? As with all UUIDs, this unique ID is "very highly likely"

* to be unique across all Android devices.? Much more so than ANDROID_ID is.

*

* The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on

* TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back

* on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a

* usable value.

*

* In some rare circumstances, this ID may change.? In particular, if the device is factory reset a new device ID

* may be generated.? In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2

* to a newer, non-buggy version of Android, the device ID may change.? Or, if a useruninstallsyourappon

* a device that has neither a proper Android ID nor a Device ID, this ID may change onreinstallation.

*

* Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT

* change after a factory reset.? Something to be aware of.

*

* Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.

*

*@seehttp://code.google.com/p/android/issues/detail?id=10603

*

*@returna UUID that may be used to uniquely identify your device for most purposes.

*/

public?UUID getDeviceUuid() {

return?uuid;

}

}

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容