Is there reason android.provider.Settings.Secure.ANDROID_ID is return the constant "android_id" instead of a 64-bit number as a hex string ?
Description : android.provider.Settings.Secure.ANDROID_ID
I am using a Samsung Galaxy S4 w /
<uses-sdk android:minSdkVersion="13" android:targetSdkVersion="19" />
Cheers
The android.provider.Settings.Secure.ANDROID_ID
is a constant that can be used in android.provider.Settings.Secure.getString(ContentResolver resolver, String name)
. By default it is set to 'android_id' since that's the name of the property containing the actual Android ID.
Use this code to get the actual id:
String androidId = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
This is just to elaborate on the answer by @MikeLaren, which is correct. But there are a couple of gotchas to be aware of, as documented in the following code, which is what I'm currently using:
// 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;
}
}
android.provider.Settings.Secure.ANDROID_ID is to big so use this answer from: https://stackoverflow.com/a/10151694/1815624
new BigInteger(string, 16).longValue()
For any value of someLong:
new BigInteger(Long.toHexString(someLong), 16).longValue() == someLong
In other words, this will return the long you sent into Long.toHexString()
for any long value, including negative numbers. It will also accept strings that are bigger than a long and silently return the lower 64 bits of the string as a long. You can just check the string length <= 16 (after trimming whitespace) if you need to be sure the input fits in a long.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.