Android: Get unique id of device


/ Published in: Objective C
Save to your folder(s)

by 'joe' from stackoverflow (http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id)


Copy this code and paste it in your HTML
  1. There are many answers to this question, most of which will only work "some" of the time, and unfortunately that's not good enough.
  2.  
  3. Based on my tests of devices (all phones, at least one of which is not activated):
  4.  
  5. All devices tested returned a value for TelephonyManager.getDeviceId()
  6. All GSM devices (all tested with a SIM) returned a value for TelephonyManager.getSimSerialNumber()
  7. All CDMA devices returned null for getSimSerialNumber() (as expected)
  8. All devices with a Google account added returned a value for ANDROID_ID
  9. All CDMA devices returned the same value (or derivation of the same value) for both ANDROID_ID and TelephonyManager.getDeviceId() -- as long as a Google account has been added during setup.
  10. I did not yet have a chance to test GSM devices with no SIM, a GSM device with no Google account added, or any of the devices in airplane mode.
  11. So if you want something unique to the device itself, TM.getDeviceId() should be sufficient. Obviously some users are more paranoid than others, so it might be useful to hash 1 or more of these identifiers, so that the string is still virtually unique to the device, but does not explicitly identify the user's actual device. For example, using String.hashCode(), combined with a UUID:
  12.  
  13. final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
  14.  
  15. final String tmDevice, tmSerial, tmPhone, androidId;
  16. tmDevice = "" + tm.getDeviceId();
  17. tmSerial = "" + tm.getSimSerialNumber();
  18. androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
  19.  
  20. UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
  21. String deviceId = deviceUuid.toString();
  22. might result in something like: 00000000-54b3-e7c7-0000-000046bffd97
  23.  
  24. It works well enough for me.
  25.  
  26. As Richard mentions below, don't forget that you need permission to read the TelephonyManager properties, so add this to your manifest:
  27.  
  28. <uses-permission android:name="android.permission.READ_PHONE_STATE" />

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.