唯一標(biāo)識碼這東西在網(wǎng)絡(luò)應(yīng)用中非常有用,例如檢測是否重復(fù)注冊之類的。
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
我們在項目過程中或多或少會使用到設(shè)備的唯一識別碼,我們希望能夠得到一個穩(wěn)定、可靠的設(shè)備唯一識別碼。今天我們將介紹幾種方式。
假設(shè)我們確實需要用到真實設(shè)備的標(biāo)識,可能就需要用到DEVICE_ID。在以前,我們的Android設(shè)備是手機,這個DEVICE_ID可以同通過TelephonyManager.getDeviceId()獲取,它根據(jù)不同的手機設(shè)備返回IMEI,MEID或者ESN碼,但它在使用的過程中會遇到很多問題:
我們也可以通過手機的Wifi或者藍牙設(shè)備獲取MAC ADDRESS作為DEVICE ID,但是并不建議這么做,因為并不是所有的設(shè)備都有Wifi,并且,如果Wifi沒有打開,那硬件設(shè)備無法返回MAC ADDRESS.
在Android 2.3可以通過android.os.Build.SERIAL獲取,非手機設(shè)備可以通過該接口獲取。
ANDROID_ID是設(shè)備第一次啟動時產(chǎn)生和存儲的64bit的一個數(shù),當(dāng)設(shè)備被wipe后該數(shù)重置
ANDROID_ID似乎是獲取Device ID的一個好選擇,但它也有缺陷:
以上四種方式都有或多或少存在的一定的局限性或者bug,在這里,有另外一種方式解決,就是使用UUID,該方法無需訪問設(shè)備的資源,也跟設(shè)備類型無關(guān)。
這種方式是通過在程序安裝后第一次運行后生成一個ID實現(xiàn)的,但該方式跟設(shè)備唯一標(biāo)識不一樣,它會因為不同的應(yīng)用程序而產(chǎn)生不同的ID,而不是設(shè)備唯一ID。因此經(jīng)常用來標(biāo)識在某個應(yīng)用中的唯一ID(即Installtion ID),或者跟蹤應(yīng)用的安裝數(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();
}
}
總結(jié)
綜合以上所述,為了實現(xiàn)在設(shè)備上更通用的獲取設(shè)備唯一標(biāo)識,我們可以實現(xiàn)這樣的一個類,為每個設(shè)備產(chǎn)生唯一的UUID,以ANDROID_ID為基礎(chǔ),在獲取失敗時以TelephonyManager.getDeviceId()為備選方法,如果再失敗,使用UUID的生成策略。
重申下,以下方法是生成Device ID,在大多數(shù)情況下Installtion ID能夠滿足我們的需求,但是如果確實需要用到Device ID,那可以通過以下方式實現(xiàn):
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static UUID uuid;
public DeviceUuidFactory(Context context) {
if( uuid ==null ) {
synchronized (DeviceUuidFactory.class) {
if( uuid == null) {
final SharedPreferences prefs = context.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 = UUID.fromString(id);
} else {
final String androidId = Secure.getString(context.getContentResolver(), 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"));
} else {
final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
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 user uninstalls your app on
* a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
*
* 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.
*
* @see http://code.google.com/p/android/issues/detail?id=10603
*
* @return a UUID that may be used to uniquely identify your device for most purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
}
代碼: 這里是你在Android里讀出 唯一的 IMSI-ID / IMEI-ID 的方法。
Java:
String myIMSI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);
// within my emulator it returns: 310995000000000
String myIMEI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMEI);
// within my emulator it returns: 000000000000000
注:android.os.SystemProperties的標(biāo)簽被打上@hide了,所以sdk中并不會存在。如果需要使用,需要有android的source code支持。