1

I want to get unique identifiers like Android Device ID, IMEI, or MAC address from an Android phone with Android version 11 using Java.
Can someone help? I need just either one unique identifier.
This is the code that I use to get IMEI:

public String getIMEI() {
        Context context = null;
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        Log.i("Testing: ", telephonyManager.getImei());
        return telephonyManager.getImei();
}

And this is the error message that I got:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
  • Is your issue specific to android R? Are you able to extract unique ID for other android versions? – Kartoos Apr 29 '23 at 09:12
  • Does this answer your question? [Best possible way to get device Id in Android](https://stackoverflow.com/questions/60503568/best-possible-way-to-get-device-id-in-android) – Kartoos Apr 29 '23 at 09:15
  • @Kartoos I successfully retrieved unique ID from Android 7 before. However, that particular code is not suitable to use for Android 11. – matchaLover Apr 29 '23 at 09:24
  • When you say code is not suitable, what is the issue? Are you getting errors? Or some other problem? – Kartoos Apr 29 '23 at 09:26
  • @Kartoos Yes, keep getting error as it always retrieves null – matchaLover Apr 29 '23 at 10:21
  • I'll add my code and the error message. – matchaLover Apr 29 '23 at 10:37
  • `Context context = null;` You are just setting the `context` to null prior to first use. Does this make sense? – Kozmotronik Apr 29 '23 at 11:42
  • If you use this method within an `Activity` derived class just use `getSystemService()` method without `context` in the beginning. Or in a fragment derived class use `reqiureContext().getSystemService()` method. – Kozmotronik Apr 29 '23 at 11:46

1 Answers1

1

As of the API 29, Google introduced new security policies to the TelephonyManager.getImei API. So it won't be available for 3rd party apps for security reasons.
Look at what is mentioned in the API's description:

Starting with API level 29, persistent device identifiers are guarded behind additional restrictions, and apps are recommended to use resettable identifiers (see Best practices for unique identifiers). This method can be invoked if one of the following requirements is met:

Kozmotronik
  • 2,080
  • 3
  • 10
  • 25