3091

Do Android devices have a unique ID, and if so, what is a simple way to access it using Java?

1

54 Answers 54

1
2
8

1.Use the telephony manager, which provides a unique id(i.e. IMEI). See the example,

import android.telephony.TelephonyManager;
import android.content.Context;
// ...
TelephonyManager telephonyManager;
telephonyManager = (TelephonyManager) getSystemService(Context.
                TELEPHONY_SERVICE);
/*
* getDeviceId() returns the unique device ID.
* For example,the IMEI for GSM and the MEID or ESN for CDMA phones.
*/
String deviceId = telephonyManager.getDeviceId();
/*
* getSubscriberId() returns the unique subscriber ID,
*/
String subscriberId = telephonyManager.getSubscriberId();

This requires android.permission.READ_PHONE_STATE to your user which can be hard to justify following the type of application you have made.

  1. Devices without telephony services like tablets must report a unique device ID that is available via android.os.Build.SERIAL since Android 2.3 Gingerbread. Some phones having telephony services can also define a serial number. Like not all Android devices have a Serial Number, this solution is not reliable.

  2. On a device first boot, a random value is generated and stored. This value is available via Settings.Secure.ANDROID_ID. It’s a 64-bit number that should remain constant for the lifetime of a device. ANDROID_ID seems a good choice for a unique device identifier because it’s available for smartphones and tablets. To retrieve the value, you can use the following code,

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

However, the value may change if a factory reset is performed on the device. There is also a known bug with a popular handset from a manufacturer where every instance has the same ANDROID_ID. Clearly, the solution is not 100% reliable.

  1. Use UUID. As the requirement for most of the applications is to identify a particular installation and not a physical device, a good solution to get the unique id for a user if to use UUID class. The following solution has been presented by Reto Meier from Google in a Google I/O presentation,
SharedPreferences sharedPrefs = context.getSharedPreferences(
         PREF_UNIQUE_ID, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);

Update : The option #1 and #2 are no longer available after android 10 as the privacy updates by google. as option 2 and 3 requires critical permission.

3
8

Get Device UUID, model number with brand name and its version number with the help of below function.

Work in Android 10 perfectly and no need to allow read phone state permission.

Code Snippets:

private void fetchDeviceInfo() {
    String uniquePseudoID = "35" +
            Build.BOARD.length() % 10 +
            Build.BRAND.length() % 10 +
            Build.DEVICE.length() % 10 +
            Build.DISPLAY.length() % 10 +
            Build.HOST.length() % 10 +
            Build.ID.length() % 10 +
            Build.MANUFACTURER.length() % 10 +
            Build.MODEL.length() % 10 +
            Build.PRODUCT.length() % 10 +
            Build.TAGS.length() % 10 +
            Build.TYPE.length() % 10 +
            Build.USER.length() % 10;

    String serial = Build.getRadioVersion();
    String uuid=new UUID(uniquePseudoID.hashCode(), serial.hashCode()).toString();
    String brand=Build.BRAND;
    String modelno=Build.MODEL;
    String version=Build.VERSION.RELEASE;
    Log.e(TAG, "fetchDeviceInfo: \n "+
            "\n uuid is : "+uuid+
            "\n brand is: "+brand+
            "\n model is: "+modelno+
            "\n version is: "+version);
}

Call Above function and to check output of above code. please see your log cat in android studio. It look likes below:

enter image description here

3
  • what is the %10 and 35+"..." in your code? i mean why you are using this approach to build unique id? why not simply combine those strings together and generate a unique UUID? is the output of this method completely unique for all devices in the world?
    – porya74
    Jun 14, 2020 at 22:13
  • 1
    Build.getRadioVersion() returns null
    – Nishant
    Sep 22, 2021 at 8:23
  • @Nishant pelase share your code here. So i can help you in this Sep 29, 2021 at 4:37
8

Android device mac id is also a unique id. It won't change even if the device itself is formatted.

Use the following code to get the mac id:

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();

Also, don't forget to add the appropriate permissions into your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
3
  • 4
    Unfortunately, this won't work if there is no current WiFi connection. From the docs (emphasis added): "Return dynamic information about the current Wi-Fi connection, if any is active."
    – Ted Hopp
    Oct 5, 2016 at 0:32
  • 3
    Also by granting root access on device, one can spoof mac address
    – user6796473
    Jul 3, 2017 at 16:33
  • Devices running Android 10 (API level 29) and higher report randomized MAC addresses to all apps that aren't device owner apps.So It wont be unique when you are in android version 10 or higher
    – Saddan
    May 23, 2020 at 6:02
5

Just a heads up for everyone reading looking for more up to date info. With Android O there are some changes to how the system manages these ids.

https://android-developers.googleblog.com/2017/04/changes-to-device-identifiers-in.html

tl;dr Serial will require PHONE permission and Android ID will change for different apps, based on their package name and signature.

And also Google has put together a nice document which provides suggestions about when to use the hardware and software ids.

https://developer.android.com/training/articles/user-data-ids.html

4

Normally, I use device unique id for my apps. But sometime I use IMEI. Both are unique numbers.

to get IMEI (international mobile equipment identifier)

public String getIMEI(Activity activity) {
    TelephonyManager telephonyManager = (TelephonyManager) activity
            .getSystemService(Context.TELEPHONY_SERVICE);
    return telephonyManager.getDeviceId();
}

to get device unique id

public String getDeviceUniqueID(Activity activity){
    String device_unique_id = Secure.getString(activity.getContentResolver(),
            Secure.ANDROID_ID);
    return device_unique_id;
}
1
  • Android Q has restricted to access for both IMEI and serial no.
    – Vakas
    May 18, 2022 at 4:54
4

I have came across this question several years ago, and have learn to implement a generalized solution based on various answers.

I have used the generalized solution for several years, in a real-world product. It serves me quite well so far. Here's the code snippet, based on various provided answers.

Note, getEmail will return null most of the time, as we didn't ask for permission explicitly.

private static UniqueId getUniqueId() {
    MyApplication app = MyApplication.instance();

    // Our prefered method of obtaining unique id in the following order.
    // (1) Advertising id
    // (2) Email
    // (2) ANDROID_ID
    // (3) Instance ID - new id value, when reinstall the app.

    ////////////////////////////////////////////////////////////////////////////////////////////
    // ADVERTISING ID
    ////////////////////////////////////////////////////////////////////////////////////////////
    AdvertisingIdClient.Info adInfo = null;
    try {
        adInfo = AdvertisingIdClient.getAdvertisingIdInfo(app);
    } catch (IOException e) {
        Log.e(TAG, "", e);
    } catch (GooglePlayServicesNotAvailableException e) {
        Log.e(TAG, "", e);
    } catch (GooglePlayServicesRepairableException e) {
        Log.e(TAG, "", e);
    }

    if (adInfo != null) {
        String aid = adInfo.getId();
        if (!Utils.isNullOrEmpty(aid)) {
            return UniqueId.newInstance(aid, UniqueId.Type.aid);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // EMAIL
    ////////////////////////////////////////////////////////////////////////////////////////////
    final String email = Utils.getEmail();
    if (!Utils.isNullOrEmpty(email)) {
        return UniqueId.newInstance(email, UniqueId.Type.eid);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // ANDROID ID
    ////////////////////////////////////////////////////////////////////////////////////////////
    final String sid = Settings.Secure.getString(app.getContentResolver(), Settings.Secure.ANDROID_ID);
    if (!Utils.isNullOrEmpty(sid)) {
        return UniqueId.newInstance(sid, UniqueId.Type.sid);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // INSTANCE ID
    ////////////////////////////////////////////////////////////////////////////////////////////
    final String iid = com.google.android.gms.iid.InstanceID.getInstance(MyApplication.instance()).getId();
    if (!Utils.isNullOrEmpty(iid)) {
        return UniqueId.newInstance(iid, UniqueId.Type.iid);
    }

    return null;
}

public final class UniqueId implements Parcelable {
    public enum Type implements Parcelable {
        aid,
        sid,
        iid,
        eid;

        ////////////////////////////////////////////////////////////////////////////
        // Handling Parcelable nicely.

        public static final Parcelable.Creator<Type> CREATOR = new Parcelable.Creator<Type>() {
            public Type createFromParcel(Parcel in) {
                return Type.valueOf(in.readString());
            }

            public Type[] newArray(int size) {
                return new Type[size];
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel parcel, int flags) {
            parcel.writeString(this.name());
        }

        // Handling Parcelable nicely.
        ////////////////////////////////////////////////////////////////////////////
    }

    public static boolean isValid(UniqueId uniqueId) {
        if (uniqueId == null) {
            return false;
        }
        return uniqueId.isValid();
    }

    private boolean isValid() {
        return !org.yccheok.jstock.gui.Utils.isNullOrEmpty(id) && type != null;
    }

    private UniqueId(String id, Type type) {
        if (org.yccheok.jstock.gui.Utils.isNullOrEmpty(id) || type == null) {
            throw new java.lang.IllegalArgumentException();
        }
        this.id = id;
        this.type = type;
    }

    public static UniqueId newInstance(String id, Type type) {
        return new UniqueId(id, type);
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + id.hashCode();
        result = 31 * result + type.hashCode();
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof UniqueId)) {
            return false;
        }

        UniqueId uniqueId = (UniqueId)o;
        return this.id.equals(uniqueId.id) && this.type == uniqueId.type;
    }

    @Override
    public String toString() {
        return type + ":" + id;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Handling Parcelable nicely.

    public static final Parcelable.Creator<UniqueId> CREATOR = new Parcelable.Creator<UniqueId>() {
        public UniqueId createFromParcel(Parcel in) {
            return new UniqueId(in);
        }

        public UniqueId[] newArray(int size) {
            return new UniqueId[size];
        }
    };

    private UniqueId(Parcel in) {
        this.id = in.readString();
        this.type = in.readParcelable(Type.class.getClassLoader());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeString(this.id);
        parcel.writeParcelable(this.type, 0);
    }

    // Handling Parcelable nicely.
    ////////////////////////////////////////////////////////////////////////////

    public final String id;
    public final Type type;
}

public static String getEmail() {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
    AccountManager accountManager = AccountManager.get(MyApplication.instance());
    Account[] accounts = accountManager.getAccountsByType("com.google");
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            String possibleEmail = account.name;
            return possibleEmail;
        }
    }

    accounts = accountManager.getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            String possibleEmail = account.name;
            return possibleEmail;
        }
    }

    return null;
} 
1
  • But does this work when the user resets his phone? in that case android id is gonna change, advertising id is resettable and email too.
    – G3n1t0
    Mar 9, 2021 at 19:09
4

Not recommended as deviceId can be used as tracking in 3rd party hands, but this is another way.

@SuppressLint("HardwareIds")
private String getDeviceID() {
    deviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                    Settings.Secure.ANDROID_ID);
    return deviceId;
}
1
  • 1
    Android is making some changes on: Settings.Secure.ANDROID_ID; On Android 8.0 (API level 26) and higher versions of the platform, a 64-bit number (expressed as a hexadecimal string), unique to each combination of app-signing key, user, and device. This means Settings.Secure.ANDROID_ID now returns IDs that are unique to the app/device combination, which makes things safer for the user. Jun 22, 2018 at 7:12
4

In order to include Android 9 I have only one idea that could still work that (probably) doesn't violate any terms, requires permissions, and works across installations and apps.

Fingerprinting involving a server should be able to identify a device uniquely. The combination of hardware information + installed apps and the installation times should do the trick. First installation times do not change unless an app is uninstalled and installed again. But this would have to be done for all apps on device in order to not be able to identify the device (ie. after a factory reset).

This is how I would go about it:

  1. Extract hardware information, application package names and first installation times.

This is how you extract all applications from Android (no permissions needed):

final PackageManager pm = application.getPackageManager();
List<ApplicationInfo> packages = 
pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo packageInfo : packages) {
    try {
        Log.d(TAG, "Installed package :" + packageInfo.packageName);
        Log.d(TAG, "Installed :" + pm.getPackageInfo(packageInfo.packageName, 0).firstInstallTime);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}
  1. You may want to make a hash of the each package name and installation timestamp combination, before sending it to the server, as it may or may not be any of your business what the user has installed on the device.
  2. Some apps (a lot actually) are system apps. These are likely to have the same installation timestamp, matching the latest system update after a factory reset. Because they have the same installation timestamp they are cannot be installed by the user, and can be filtered out.
  3. Send the info to the server and let it look for nearest match amongst previously stored info. You need to make a threshold when comparing with previously stored device info as apps are installed and uninstalled. But my guess is that this threshold can be very low, as any package name and first time installation timestamp combination alone will be pretty unique for a device, and apps are not that frequently installed and uninstalled. Having multiple apps just increases the probability of being unique.
  4. Return the generated unique id for the match, or generate a unique id, store with device info and return this new id.

NB: This is a non-tested and non-proved method! I am confident it will work, but I am also pretty sure that if this catches on, they will close it down one way or another.

4

Here is a simple answer to get AAID, tested working properly June 2019

 AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String token = null;
            Info adInfo = null;
            try {
                adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
            } catch (IOException e) {
                // ...
            } catch ( GooglePlayServicesRepairableException e) {
                // ...
            } catch (GooglePlayServicesNotAvailableException e) {
                // ...
            }
            String android_id = adInfo.getId();
            Log.d("DEVICE_ID",android_id);

            return android_id;
        }

        @Override
        protected void onPostExecute(String token) {
            Log.i(TAG, "DEVICE_ID Access token retrieved:" + token);
        }

    };
    task.execute();

read full answer in detail here:

3

If you add: 

Settings.Secure.getString(context.contentResolver,
    Settings.Secure.ANDROID_ID)

Android Lint will give you the following warning:

Using getString to get device identifiers is not recommended. Inspection info: Using these device identifiers is not recommended other than for high value fraud prevention and advanced telephony use-cases. For advertising use-cases, use AdvertisingIdClient$Info#getId and for analytics, use InstanceId#getId.

So, you should avoid using this.

As mentioned in Android Developer documentation :

1: Avoid using hardware identifiers.

In most use cases, you can avoid using hardware identifiers, such as SSAID (Android ID) and IMEI, without limiting required functionality.

2: Only use an Advertising ID for user profiling or ads use cases.

When using an Advertising ID, always respect users' selections regarding ad tracking. Also, ensure that the identifier cannot be connected to personally identifiable information (PII), and avoid bridging Advertising ID resets.

3: Use an Instance ID or a privately stored GUID whenever possible for all other use cases, except for payment fraud prevention and telephony.

For the vast majority of non-ads use cases, an Instance ID or GUID should be sufficient.

4: Use APIs that are appropriate for your use case to minimize privacy risk.

Use the DRM API for high-value content protection and the SafetyNet APIs for abuse protection. The SafetyNet APIs are the easiest way to determine whether a device is genuine without incurring privacy risk.

2
String SERIAL_NUMER = Build.SERIAL;

Returns SERIAL NUMBER as a string which unique in each device.

0
2

Serial Number is a unique device ID available via android.os.Build.SERIAL.

public static String getSerial() {
    String serial = "";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        serial = Build.getSerial();
    }else{ 
        serial = Build.SERIAL;    
    }
    return serial;
}

Make sure you have READ_PHONE_STATE permission before calling getSerial().

NOTE:- It is Not available with Devices without telephony (like wifi only tablets).

1
2

For completeness, here is how you can get the Id in Xamarin.Android and C#:

var id = Settings.Secure.GetString(ContentResolver, Settings.Secure.AndroidId);

Or if you are not within an Activity:

var id = Settings.Secure.GetString(context.ContentResolver, Settings.Secure.AndroidId);

Where context is the passed in context.

1

Get the device ID only once, and then store it in a database or a file. In this case, if it is the first boot of the app, it generates an ID and stores it. Next time, it will only take the ID stored in the file.

1
  • 7
    The idea is to have an ID that survives the app being uninstalled and re installed. Saving an ID to a data base doesn't help because the data base is removed when the app is uninstalled.
    – Ted Hopp
    Oct 21, 2013 at 12:17
1
android.telephony.TelephonyManager.getDeviceId()

This will return whatever string uniquely identifies the device (IMEI on GSM, MEID for CDMA).

You'll need the following permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
1
  • 4
    It's deprecated
    – Googlian
    Oct 23, 2019 at 7:22
1

Yes, every Android device have a unique serial numbers you can able to get it from this code. Build.SERIAL. Note that it was only added in API level 9, and it may not be present on all devices. To get a unique ID on earlier platforms, you'll need to read something like the MAC address or IMEI.

1

After much searching. I realized there is no sure way to have a unique ID.

Suppose we want each user to be able to use the application on only one phone.

What I do is:

When a user registers in my app, I save the current time as a unique ID both on the server and in the application database.

When the user tries to login on another phone, I fetch the user information from the server and realize that this user has already been logged in because the unique ID field is full, so show him/her a dialog that he/she has already logged in to another device, whether he wants to leave the previous session or not, if he says yes, I will create a new unique ID for him and update the unique ID details on the server.

In my own app, I get the user profile from the server every time it runs. If the unique ID stored on the server is different from the unique ID stored in the application database, I will automatically log out of the user.

3
  • What if the user re-installs the app on his device? This approach will fail.
    – Vakas
    May 18, 2022 at 5:11
  • @Vakas the user is signing in to the app with credentials so re-installing the app is not an issue, since they would have to log in again.
    – lasec0203
    Jun 8, 2022 at 9:23
  • 1
    @lasec0203 We have a financial app where people try to clone and bypass securities, so we need to have a check which user is signing how many times from a device. In our case, this technique fails.
    – Vakas
    Jun 30, 2022 at 11:17
1

This example demonstrates how to get and store device ID in Android but I using Kotlin.

      val textView: TextView = findViewById(R.id.textView)
      val uniqueId: String = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
      textView.text = "Device ID: $uniqueId"
2
  • but this can change if app is re-installed Feb 12 at 5:35
  • If you wanna avoid to changing it by re-installing, you should take unique ID from Firebase Mar 22 at 7:54
1

Generate Device Identifier

 private String generateDeviceIdentifier() {
    String uniqueDevicePseudoID = "35" +
            Build.BOARD.length() % 10 +
            Build.BRAND.length() % 10 +
            Build.DEVICE.length() % 10 +
            Build.DISPLAY.length() % 10 +
            Build.HOST.length() % 10 +
            Build.ID.length() % 10 +
            Build.MANUFACTURER.length() % 10 +
            Build.MODEL.length() % 10 +
            Build.PRODUCT.length() % 10 +
            Build.TAGS.length() % 10 +
            Build.TYPE.length() % 10 +
            Build.USER.length() % 10;

    String serial = Build.getRadioVersion();
    String uuid = new UUID(uniqueDevicePseudoID.hashCode(), serial.hashCode()).toString();
    Log.e("DeviceIdentifier ", "\nDeviceIdentifier uuid is : " + uuid);
    return uuid;
}

Output

DeviceIdentifier uuid is : 00000000-36ab-9c3c-0000-0000714a4f37

enter image description here

0

Check for SystemInfo.deviceUniqueIdentifier

Documentation: http://docs.unity3d.com/Documentation/ScriptReference/SystemInfo-deviceUniqueIdentifier.html

A unique device identifier. It is guaranteed to be unique for every device (Read Only).

iOS: on pre-iOS7 devices it will return hash of MAC address. On iOS7 devices it will be UIDevice identifierForVendor or, if that fails for any reason, ASIdentifierManager advertisingIdentifier.

0

To get a user id you can use Google Play Licensing Library.

To download this library open SDK Manager => SDK Tools. The path to downloaded library files is:

path_to_android_sdk_on_your_pc/extras/google/market_licensing/library

Include the library in your project (you can simply copy its files).

Next you need some implementation of Policy interface (you can simply use one of two files from the library: ServerManagedPolicy or StrictPolicy).

User id will be provided for you inside processServerResponse() function:

public void processServerResponse(int response, ResponseData rawData) {
    if(rawData != null) {
        String userId = rawData.userId
        // use/save the value
    }
    // ...
}

Next you need to construct the LicenseChecker with a policy and call checkAccess() function. Use MainActivity.java as an example of how to do it. MainActivity.java is located inside this folder:

path_to_android_sdk_on_your_pc/extras/google/market_licensing/sample/src/com/example/android/market/licensing

Don't forget to add CHECK_LICENSE permission to your AndroidManifest.xml.

More about Licensing Library: https://developer.android.com/google/play/licensing

0

Android restricts the hardware related Id after Android O, therefore, Android_Id is the solution for unique id but it has an issue when reflector the device it will generate new android_id to overcome this problem we can use the DRUMID.

val WIDEVINE_UUID = UUID(-0x121074568629b532L, -0x5c37d8232ae2de13L)
val drumIDByteArray = MediaDrm(WIDEVINE_UUID).getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID)

val drumID = android.util.Base64.encodeToString(drumIDByteArray,android.util.Base64.DEFAULT)
-2

You will get the wifi mac address by using the following code, regardless whether you used a randomized address when you tried to connect to the wifi or not, and regardless whether the wifi was turned on or off.

I used a method from the link below, and added a small modification to get the exact address instead of the randomized one:

Getting MAC address in Android 6.0

public static String getMacAddr() {
StringBuilder res1 = new StringBuilder();
try {
List<NetworkInterface> all =     
Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {    
if (!nif.getName().equalsIgnoreCase("p2p0")) continue;

        byte[] macBytes = nif.getHardwareAddress();
        if (macBytes == null) {
            continue;
        }

        res1 = new StringBuilder();
        for (byte b : macBytes) {
            res1.append(String.format("%02X:",b));
        }

        if (res1.length() > 0) {
            res1.deleteCharAt(res1.length() - 1);
        }
    }
} catch (Exception ex) {
}
return res1.toString();

}

1
-3

package com.aapbd.appbajarlib.common;

import android.os.Build;

import java.util.Locale;
import java.util.UUID;

public class DeviceID {



    public  static String getDeviceLanguage()
    {

        Locale locale=Locale.getDefault();
        return locale.getDisplayLanguage();

    }

    public  static String getDeviceCountry()
    {

        Locale locale=Locale.getDefault();
        return locale.getDisplayCountry();

    }


    public static String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    public static String getAndroidVersion() {

            String release = Build.VERSION.RELEASE;
            int sdkVersion = Build.VERSION.SDK_INT;
            return sdkVersion + " (" + release +")";

    }

    public static int getAndroidAPILevel() {

        int sdkVersion = Build.VERSION.SDK_INT;
        return sdkVersion;

    }




    private static String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }


    /**
     * Return pseudo unique ID
     * @return ID
     */
    public static String getUniquePsuedoID() {
        // If all else fails, if the user does have lower than API 9 (lower
        // than Gingerbread), has reset their device or 'Secure.ANDROID_ID'
        // returns 'null', then simply the ID returned will be solely based
        // off their Android device information. This is where the collisions
        // can happen.
        // Thanks http://www.pocketmagic.net/?p=1662!
        // Try not to use DISPLAY, HOST or ID - these items could change.
        // If there are collisions, there will be overlapping data
        String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);

        // Thanks to @Roman SL!
        // http://stackoverflow.com/a/4789483/950427
        // Only devices with API >= 9 have android.os.Build.SERIAL
        // http://developer.android.com/reference/android/os/Build.html#SERIAL
        // If a user upgrades software or roots their device, there will be a duplicate entry
        String serial = null;
        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();

            // Go ahead and return the serial for api => 9
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            // String needs to be initialized
            serial = "serial"; // some value
        }

        // Thanks @Joe!
        // http://stackoverflow.com/a/2853253/950427
        // Finally, combine the values we have found by using the UUID class to create a unique identifier
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

}

I am using this and it's working over the last 6 years.

Here's the library: https://github.com/nillbiplob/AppBajarLIB

1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.