Home > Software engineering >  how to get device Imei Number and deviceId in android using telephone manager
how to get device Imei Number and deviceId in android using telephone manager

Time:04-23

HI i am trying to get device Imei and device ID using below code

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_PHONE_NUMBERS, Manifest.permission.READ_PHONE_STATE}, REQUEST_CODE);

        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {


        }
        String telephoneNumber = telephonyManager.getLine1Number();
        String imeI= telephonyManager.getImei();

I am able to read phone number but i am unable to get imei number or device id i am getting below Exception or error . Method threw 'java.lang.SecurityException' exception. please help me in this .

CodePudding user response:

As of API 29, there's only certain apps that can get the IMEI:

  • If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission. This is a privlidged permission, so your app has to be a preinstalled app or you need to root your device and install it as one. This will not work for a Play Store app
  • If the app is the Device Owner or Profile Owner (again, does not work for Play Store apps).
  • If the app has carrier privlidges (again, does not work for Play Store apps
  • If the app is the default SMS app (can be a play store app, but if you aren't an SMS app this won't work).

Any call to get the IMEI if those conditions aren't met will either return null or throw an exception. This is for privacy and security of the users, you should not be able to track a device across device resets.

CodePudding user response:

You have to call android.telephony.TelephonyManager.getDeviceId().

This will return the device IMEI.

But to do this in addition to the request for permissions, which you already have, you have to add the following permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

  • Related