这是一个非常重要和有趣的问题,所以想详细回答一下。
有几种唯一检测Android设备的方法,但问题是由于各种原因,它们中的大多数都不可靠。
i) IMEI
这是迄今为止最常用的方法,但仅适用于手机,需要此不必要的权限android.permission.READ_PHONE_STATE
ii) Android ID
这也可以在恢复出厂设置或设备已植根时更改。不是一种非常可靠的唯一性方法。
iii) WLAN 和蓝牙 MAC 地址
这要求设备具有这些功能并获得android.permission.ACCESS_WIFI_STATE 和android.permission.BLUETOOTH 等权限。如果 wifi 或蓝牙关闭,这也将不起作用。
iv) 电话号码或电子邮件 ID
这是确定唯一性最不可靠的方法,如果不是完全必要的话,也不应该是一种选择方法。
那么现在的出路是什么,伪唯一 ID。您无需任何额外权限即可从设备创建自己的“几乎唯一 ID”。
听起来不错?让我们直接进入方法。
/**
* Return pseudo unique ID
* @return ID
*/
public static String getUniquePsuedoID() {
// If all else fails, if the user does have lower than API 9 (lower
// than Gingerbread), has reset their device or 'Secure.ANDROID_ID'
// returns 'null', then simply the ID returned will be solely based
// off their Android device information. This is where the collisions
// can happen.
// Thanks http://www.pocketmagic.net/?p=1662!
// Try not to use DISPLAY, HOST or ID - these items could change.
// If there are collisions, there will be overlapping data
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
// Thanks to @Roman SL!
// http://stackoverflow.com/a/4789483/950427
// Only devices with API >= 9 have android.os.Build.SERIAL
// http://developer.android.com/reference/android/os/Build.html#SERIAL
// If a user upgrades software or roots their device, there will be a duplicate entry
String serial = null;
try {
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
// Go ahead and return the serial for api => 9
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
} catch (Exception exception) {
// String needs to be initialized
serial = "serial"; // some value
}
// Thanks @Joe!
// http://stackoverflow.com/a/2853253/950427
// Finally, combine the values we have found by using the UUID class to create a unique identifier
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
在为任何 Android 设备生成伪唯一 ID 时会考虑各种因素。但这并不完美。
这些 ID 可能会发生冲突,但这种情况非常罕见,非常非常罕见。所以从技术上讲,这是您在大多数用例中都可以依赖的东西。