Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link

read imei in android programmatically

read imei in android programmatically


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;

import androidx.core.app.ActivityCompat;

public class ImeiReader {
    private Context mContext;

    public ImeiReader(Context context) {
        mContext = context;
    }

    public String getImei() {
        TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            return telephonyManager.getImei();
        }

        return null;
    }
}

        

In this example, we define a ImeiReader class that takes a Context parameter in the constructor. The getImei() method retrieves the IMEI of the device using the TelephonyManager class, and checks for the READ_PHONE_STATE permission before returning the IMEI. If the permission is not granted, the method returns null.

To use the ImeiReader class, you can create an instance of it and call the getImei() method:


  ImeiReader imeiReader = new ImeiReader(this);
String imei = imeiReader.getImei();

  

Note that you need to request the READ_PHONE_STATE permission in your AndroidManifest.xml file and ask the user to grant it at runtime if your app targets Android 11 (API level 30) or higher.

Post a Comment