Sunday, September 9, 2012

Android Device specific unique id generation


//generate unique id..
public static String getUniqueID(Context context) {

TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);

String uniqueID = null;

//http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID
uniqueID = android.provider.Settings.Secure.getString(
context.getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);

if (uniqueID == null) {

String deviceID = "" + telephonyManager.getDeviceId();
String simSerialID = "" + telephonyManager.getSimSerialNumber();
String androidID = ""
+ android.provider.Settings.Secure.getString(
context.getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);

UUID deviceUuid = new UUID(androidID.hashCode(), ((long) deviceID
.hashCode() << 32)
| simSerialID.hashCode());

if (deviceUuid.toString() != null) {
uniqueID = ((deviceUuid.toString().length() > 0) && (deviceUuid
.toString().length() >= 32)) ? deviceUuid.toString()
.substring(0, 32) : deviceUuid.toString();
}
}
return uniqueID;
}

Sometimes, I have found that the unique id generation for a android device fails. In this case this function is pretty useful as a alternate way of generating a unique id.

No comments:

Post a Comment