Android是否有唯一的设备ID,如果有的话,该怎样快速有效获取?
Settings.Secure#ANDROID_ID 返回Android ID ,是一个64位的16进制字符串
1
2
3
|
import
android.provider.Settings.Secure; private
String android_id = Secure.getString(getContext().getContentResolver(),Secure.ANDROID_ID); |
关于这个问题有很多的答案,不过其中大部分将只能算是答对了一部分,还不够好。
根据我在很多设备上的测试(所有的电话,至少有一个是无效的)
- 所有设备针对 TelephonyManager.getDeviceId() 测试都有返回值
- 所有GSM设备(都有SIM卡)针对 TelephonyManager.getSimSerialNumber() 测试都有返回值
- 所有CDMA设备针对 getSimSerialNumber() 测试返回 NULL(预期中的)
- 所有有谷歌帐户的设备都返回了 ANDROID_ID 值
- 所有的CDMA设备针对 ANDROID_ID 和 TelephonyManager.getDeviceId() 都返回相同的值(或派生自同一个值) - 前提是安装过程中已经添加了谷歌帐户。
- 我还没有机会测试没有SIM卡的GSM设备,没有谷歌账户的GSM设备,以及任何在飞行模式下的设备。
1
2
3
4
5
6
7
8
9
|
final
TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE); final
String tmDevice, tmSerial, androidId; tmDevice
= ""
+ tm.getDeviceId(); tmSerial
= ""
+ tm.getSimSerialNumber(); androidId
= ""
+ android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); UUID
deviceUuid = new
UUID(androidId.hashCode(), (( long )tmDevice.hashCode()
<< 32 )
| tmSerial.hashCode()); String
deviceId = deviceUuid.toString(); |
结果可能类似 :00000000-54b3-e7c7-0000-000046bffd97
对我来说这种方式已经足够了
别忘了增加权限,用于读取 TelephonyManager properties,在manifest 中增加下面一行:
1
|
< uses-permission
android:name = "android.permission.READ_PHONE_STATE"
/> |