如何获取Android设备唯一ID?
问题
每一个android设备都有唯一ID吗?如果有?怎么用java最简单取得呢?
如何取得android唯一码?
好处:
- 1.不需要特定权限.
- 2.在99.5% Android装置(包括root过的)上,即API => 9,保证唯一性.
- 3.重装app之后仍能取得相同唯一值.
伪代码:
1 2 3 4 5 6 7
| if API => 9/10: (99.5% of devices) return unique ID containing serial id (rooted devices may be different) else return unique ID of build information (may overlap data - API < 9)
|
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| * Return pseudo unique ID * @return ID */public static String getUniquePsuedoID() { 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); String serial = null; try { serial = android.os.Build.class.getField("SERIAL").get(null).toString(); return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString(); } catch (Exception exception) { serial = "serial"; } return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();}
|
###回答2
好处:
- 1.不需要特定权限.
- 2.在100% Android装置(包括root过的)上,保证唯一性.
坏处
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| private static String uniqueID = null; private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID"; public synchronized static String id(Context context) { if (uniqueID == null) { SharedPreferences sharedPrefs = context.getSharedPreferences( PREF_UNIQUE_ID, Context.MODE_PRIVATE); uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null); if (uniqueID == null) { uniqueID = UUID.randomUUID().toString(); Editor editor = sharedPrefs.edit(); editor.putString(PREF_UNIQUE_ID, uniqueID); editor.commit(); } } return uniqueID; }
|
###回答3(需要有电话卡)
好处:
1.重装app之后仍能取得相同唯一值.
代码:
1 2 3 4 5 6 7
| 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();
|
谨记:要取得以下权限
1
| <uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
stackoverflow链接:
http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id