2

I have found two ways to get device id in android but I do not which one of them better and what are the differences between them

Method 1

public static String getDeviceId2(Context context) {


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

        return androidId;
    }

Method 2

public static String getDeviceId(Context context) {

        if (PermissionManager.getInstance().hasSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == true) {

            return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        } else {
            return "";
        }
    }
Amira Elsayed Ismail
  • 8,304
  • 26
  • 74
  • 144
  • Does anyone know a work around for this warning on method 1? - 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. – C. Skjerdal Nov 29 '18 at 19:15

2 Answers2

2

ANDROID_ID

Can change. In 8.0 it changes upon reinstall of your app

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. Values of ANDROID_ID are scoped by signing key and user. The value may change if a factory reset is performed on the device or if an APK signing key changes. For more information about how the platform handles ANDROID_ID in Android 8.0 (API level 26) and higher, see Android 8.0 Behavior Changes.

Note: For apps that were installed prior to updating the device to a version of Android 8.0 (API level 26) or higher, the value of ANDROID_ID changes if the app is uninstalled and then reinstalled after the OTA. To preserve values across uninstalls after an OTA to Android 8.0 or higher, developers can use Key/Value Backup.

getDeviceId()

Is deprecated in 8.0

tyczj
  • 66,691
  • 50
  • 172
  • 271
1

First method is the right one. Second won't work on devices without sim cards

Alex Orlov
  • 17,801
  • 7
  • 53
  • 44