Android获取设备唯一ID的几种方式

论坛 期权论坛 脚本     
匿名网站用户   2020-12-20 08:33   11   0

先来看看几种比较单一的方式:


IMEI

方式:TelephonyManager.getDeviceId():

问题

范围:只能支持拥有通话功能的设备,对于平板不可以。

持久性:返厂,数据擦除的时候不彻底,保留了原来的标识。

权限:需要权限:android.permission.READ_PHONE_STATE

bug: 有些厂家的实现有bug,返回一些不可用的数据


Mac地址

ACCESS_WIFI_STATE权限

有些设备没有WiFi,或者蓝牙,就不可以,如果WiFi没有打开,硬件也不会返回Mac地址,不建议使用


ANDROID_ID

2.2(Froyo,8)版本系统会不可信,来自主要生产厂商的主流手机,至少有一个普遍发现的bug,这些有问题的手机相同的ANDROID_ID: 9774d56d682e549c

但是如果返厂的手机,或者被root的手机,可能会变


Serial Number

从Android 2.3 (“Gingerbread”)开始可用,可以通过android.os.Build.SERIAL获取,对于没有通话功能的设备,它会

返回一个唯一的device ID,


以下几个是stackoverflow上评论较多的几个,没贴完,还有其他,综合的,用到以上的部分方式:

地址:http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id

google官方的相关博客:http://android-developers.blogspot.com/2011/03/identifying-app-installations.html

有兴趣的朋友可以再仔细看看


支持率比较高的(支持票数157):androidID --> 剔除2.2版本(API 8)中有问题的手机,使用UUID替代

[java] view plain copy
在CODE上查看代码片派生到我的代码片
  1. import android.content.Context;
  2. import android.content.SharedPreferences;
  3. import android.provider.Settings.Secure;
  4. import android.telephony.TelephonyManager;
  5. import java.io.UnsupportedEncodingException;
  6. import java.util.UUID;
  7. public class DeviceUuidFactory {
  8. protected static final String PREFS_FILE = "device_id.xml";
  9. protected static final String PREFS_DEVICE_ID = "device_id";
  10. protected static volatile UUID uuid;
  11. public DeviceUuidFactory(Context context) {
  12. if (uuid == null) {
  13. synchronized (DeviceUuidFactory.class) {
  14. if (uuid == null) {
  15. final SharedPreferences prefs = context
  16. .getSharedPreferences(PREFS_FILE, 0);
  17. final String id = prefs.getString(PREFS_DEVICE_ID, null);
  18. if (id != null) {
  19. // Use the ids previously computed and stored in the
  20. // prefs file
  21. uuid = UUID.fromString(id);
  22. } else {
  23. final String androidId = Secure.getString(
  24. context.getContentResolver(), Secure.ANDROID_ID);
  25. // Use the Android ID unless it's broken, in which case
  26. // fallback on deviceId,
  27. // unless it's not available, then fallback on a random
  28. // number which we store to a prefs file
  29. try {
  30. if (!"9774d56d682e549c".equals(androidId)) {
  31. uuid = UUID.nameUUIDFromBytes(androidId
  32. .getBytes("utf8"));
  33. } else {
  34. final String deviceId = ((TelephonyManager)
  35. context.getSystemService(
  36. Context.TELEPHONY_SERVICE)
  37. .getDeviceId();
  38. uuid = deviceId != null ? UUID
  39. .nameUUIDFromBytes(deviceId
  40. .getBytes("utf8")) : UUID
  41. .randomUUID();
  42. }
  43. } catch (UnsupportedEncodingException e) {
  44. throw new RuntimeException(e);
  45. }
  46. // Write the value out to the prefs file
  47. prefs.edit()
  48. .putString(PREFS_DEVICE_ID, uuid.toString())
  49. .commit();
  50. }
  51. }
  52. }
  53. }
  54. }
  55. /**
  56. * Returns a unique UUID for the current android device. As with all UUIDs,
  57. * this unique ID is "very highly likely" to be unique across all Android
  58. * devices. Much more so than ANDROID_ID is.
  59. *
  60. * The UUID is generated by using ANDROID_ID as the base key if appropriate,
  61. * falling back on TelephonyManager.getDeviceID() if ANDROID_ID is known to
  62. * be incorrect, and finally falling back on a random UUID that's persisted
  63. * to SharedPreferences if getDeviceID() does not return a usable value.
  64. *
  65. * In some rare circumstances, this ID may change. In particular, if the
  66. * device is factory reset a new device ID may be generated. In addition, if
  67. * a user upgrades their phone from certain buggy implementations of Android
  68. * 2.2 to a newer, non-buggy version of Android, the device ID may change.
  69. * Or, if a user uninstalls your app on a device that has neither a proper
  70. * Android ID nor a Device ID, this ID may change on reinstallation.
  71. *
  72. * Note that if the code falls back on using TelephonyManager.getDeviceId(),
  73. * the resulting ID will NOT change after a factory reset. Something to be
  74. * aware of.
  75. *
  76. * Works around a bug in Android 2.2 for many devices when using ANDROID_ID
  77. * directly.
  78. *
  79. * @see http://code.google.com/p/android/issues/detail?id=10603
  80. *
  81. * @return a UUID that may be used to uniquely identify your device for most
  82. * purposes.
  83. */
  84. public UUID getDeviceUuid() {
  85. return uuid;
  86. }
  87. }


根据版本进行判断的方式:Serial序列号-->UUID (支持数31)

通过Serial 即可,在覆盖率上,你已经成功的获得了98.4%的用户,剩下的1.6%的用户系统是在9 以下的。

通过AndroidID获取,前面已经说过,在8上,有些商家的手机会有一些bug,返回相同的AndroidID,如果Serial和AndroidID都不行

[java] view plain copy
在CODE上查看代码片派生到我的代码片
  1. /**
  2. * Return pseudo unique ID
  3. * @return ID
  4. */
  5. public static String getUniquePsuedoID()
  6. {
  7. // If all else fails, if the user does have lower than API 9 (lower
  8. // than Gingerbread), has reset their phone or 'Secure.ANDROID_ID'
  9. // returns 'null', then simply the ID returned will be solely based
  10. // off their Android device information. This is where the collisions
  11. // can happen.
  12. // Thanks http://www.pocketmagic.net/?p=1662!
  13. // Try not to use DISPLAY, HOST or ID - these items could change.
  14. // If there are collisions, there will be overlapping data
  15. 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);
  16. // Thanks to @Roman SL!
  17. // http://stackoverflow.com/a/4789483/950427
  18. // Only devices with API >= 9 have android.os.Build.SERIAL
  19. // http://developer.android.com/reference/android/os/Build.html#SERIAL
  20. // If a user upgrades software or roots their phone, there will be a duplicate entry
  21. String serial = null;
  22. try
  23. {
  24. serial = android.os.Build.class.getField("SERIAL").get(null).toString();
  25. // Go ahead and return the serial for api => 9
  26. return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
  27. }
  28. catch (Exception e)
  29. {
  30. // String needs to be initialized
  31. serial = "serial"; // some value
  32. }
  33. // Thanks @Joe!
  34. // http://stackoverflow.com/a/2853253/950427
  35. // Finally, combine the values we have found by using the UUID class to create a unique identifier
  36. return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
  37. }


不用READ_PHONE_STATE权限直接获取ROM信息的方式:(支持率较低 16)

[java] view plain copy
在CODE上查看代码片派生到我的代码片
  1. String m_szDevIDShort = "35" + //we make this look like a valid IMEI
  2. Build.BOARD.length()%10+ Build.BRAND.length()%10 +
  3. Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
  4. Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
  5. Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
  6. Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
  7. Build.TAGS.length()%10 + Build.TYPE.length()%10 +
  8. Build.USER.length()%10 ; //13 digits


最后贴上自己在项目中用的:

[java] view plain copy
在CODE上查看代码片派生到我的代码片
  1. public static String getDeviceId(Context context) {
  2. String deviceId = "";
  3. <span style="white-space:pre"> </span>if (deviceId != null && !"".equals(deviceId)) {
  4. <span style="white-space:pre"> </span>return deviceId;
  5. <span style="white-space:pre"> </span>}
  6. if (deviceId == null || "".equals(deviceId)) {
  7. try {
  8. deviceId = getLocalMac(context).replace(":", "");
  9. } catch (Exception e) {
  10. e.printStackTrace();
  11. }
  12. }
  13. if (deviceId == null || "".equals(deviceId)) {
  14. try {
  15. deviceId = getAndroidId(context);
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. if (deviceId == null || "".equals(deviceId)) {
  21. if (deviceId == null || "".equals(deviceId)) {
  22. UUID uuid = UUID.randomUUID();
  23. deviceId = uuid.toString().replace("-", "");
  24. writeDeviceID(deviceId);
  25. }
  26. }
  27. return deviceId;
  28. }


[java] view plain copy
在CODE上查看代码片派生到我的代码片
  1. // IMEI码
  2. private static String getIMIEStatus(Context context) {
  3. TelephonyManager tm = (TelephonyManager) context
  4. .getSystemService(Context.TELEPHONY_SERVICE);
  5. String deviceId = tm.getDeviceId();
  6. return deviceId;
  7. }
  8. // Mac地址
  9. private static String getLocalMac(Context context) {
  10. WifiManager wifi = (WifiManager) context
  11. .getSystemService(Context.WIFI_SERVICE);
  12. WifiInfo info = wifi.getConnectionInfo();
  13. return info.getMacAddress();
  14. }
  15. // Android Id
  16. private static String getAndroidId(Context context) {
  17. String androidId = Settings.Secure.getString(
  18. context.getContentResolver(), Settings.Secure.ANDROID_ID);
  19. return androidId;
  20. }
  21. public static void saveDeviceID(String str) {
  22. try {
  23. FileOutputStream fos = new FileOutputStream(file);
  24. Writer out = new OutputStreamWriter(fos, "UTF-8");
  25. out.write(str);
  26. out.close();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. public static String readDeviceID() {
  32. StringBuffer buffer = new StringBuffer();
  33. try {
  34. FileInputStream fis = new FileInputStream(file);
  35. InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
  36. Reader in = new BufferedReader(isr);
  37. int i;
  38. while ((i = in.read()) > -1) {
  39. buffer.append((char) i);
  40. }
  41. in.close();
  42. return buffer.toString();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. return null;
  46. }
  47. }

对于获取设备唯一ID并没有绝对的方案,这一点在android的官方博客中也提到了,不过以上几种方案,应该可以满足平时的需求,大家可以选择其中自己认为比较好的,用于自己的项目中。不知道其他朋友在项目中是如何处理的,欢迎交流讨论。
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP