android.provider.Settings.Secure.ANDROID_ID返回“android_id”

2022-09-03 17:36:26

有没有理由android.provider.Settings.Secure.ANDROID_ID返回常量“android_id”而不是64位数字作为十六进制字符串?

描述 : android.provider.Settings.Secure.ANDROID_ID

  • 一个 64 位数字(作为十六进制字符串),在用户首次设置设备时随机生成,并应在用户设备的生存期内保持不变。如果在设备上执行恢复出厂设置,则该值可能会更改。

我正在使用三星银河S4 w /

 <uses-sdk android:minSdkVersion="13"  android:targetSdkVersion="19" />

干杯


答案 1

是一个可在 中使用的常量。默认情况下,它设置为“android_id”,因为这是包含实际Android ID的属性的名称。android.provider.Settings.Secure.ANDROID_IDandroid.provider.Settings.Secure.getString(ContentResolver resolver, String name)

使用以下代码获取实际 ID:

String androidId = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID); 

答案 2

这只是为了详细说明@MikeLaren的答案,这是正确的。但是有一些需要注意的问题,如下面的代码中所述,这就是我当前正在使用的内容:

  // Get the unique (supposedly) ID for this Android device/user combination
  long androidId = convertHexToLong(Settings.Secure.getString(
                         _applicationContext.getContentResolver(), Settings.Secure.ANDROID_ID));

....

   // Method to convert a 16-character hex string into a Java long. This only took me about an hour,
   // due to a known bug in Java that it took them 13 years to fix, and still isn't fixed in the
   // version of Java used for Android development.
   // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4215269
   // http://stackoverflow.com/questions/1410168/how-to-parse-negative-long-in-hex-in-java
   // On top of that it turns out that on a HTC One the Settings.Secure.ANDROID_ID string may be 15
   // digits instead of 16!
   private long convertHexToLong(String hexString) {

      hexString = "0000000000000000" + hexString;
      int i = hexString.length();
      hexString = hexString.substring(i - 16, i);

      try {
         return Long.parseLong(hexString.substring(0, 8), 16) << 32 |
                Long.parseLong(hexString.substring(8, 16), 16);

      } catch (Exception e) {
         return 0L;
      }
   }

推荐