Design Pattern – Getting a Unique Id for Android Device

It sometimes becomes necessary to identify an Android Device depending on our use case or application requirements. There are some use cases where we might need device identification.

For example, when you want to :

1-Identify an Android user to store games scores on a server

2-Track apps installation

There are several types of methods that exist to uniquely identify an Android Device like through  Mac Address, Unique Telephony Number (IMEI, MEID, ESN, IMSI), Build.SERIAL, UUI, ANDROID_ID, etc, but over the time most of them have been put under restriction by the Android team for security reasons.

Two recommended ways are –

1-Android Id

2- UUID

  1. Android Id

It gets randomly generated and stored on a device first boot, This value is available via Settings.Secure.ANDROID_ID. It is a 64-bit number that remains constant for the lifetime of a device. ANDROID_ID seems a good choice for a unique device identifier because it is available for smartphones and tablets. To retrieve the value, use  the following code :

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

 

Or 

override fun getDeviceId(): String = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID )

 

Limitations —  Android id value may change if a device gets rooted or factory reset.

  1. UUID

If our requirement is to identify a particular installation and not a physical device, a good solution to get a unique id for a user is to use the UUID class of Java. We can get the UUID and store it in our application using Shared Preference or any other mechanism for a particular installation.

private static String uniqueID = null;

private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";

public synchronized static String id(Context context) {

   if (uniqueID == null) {

      SharedPreferences sharedPrefs = context.getSharedPreferences(

         PREF_UNIQUE_ID, Context.MODE_PRIVATE);

      uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);

      if (uniqueID == null) {

         uniqueID = UUID.randomUUID().toString();

         Editor editor = sharedPrefs.edit();

         editor.putString(PREF_UNIQUE_ID, uniqueID);

         editor.commit();
            //or
 editor.apply();

      }
   }
    return uniqueID;
}

 

 

UUID.randomUUID() method generates a unique identifier for a specific installation.

Leave a Reply