Using Telephony Manager in android to find IMEI number

Arsalan picture Arsalan · Sep 22, 2011 · Viewed 61.7k times · Source

I m very new to Android Development. I want to find the IMEI number of the phone and using "android.telephony.TelephonyManager;".

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();

Now the compiler says. Context cannot be resolved to a variable. Any one can help me ? What step I m missing I have also included user permission in XML.

Answer

Houcine picture Houcine · Sep 22, 2011

Verify your Imports , you should import : android.content.Context ,

And then use this code :

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
String imei = tm.getDeviceId();
//get The Phone Number
String phone = tm.getLine1Number();

Or directly : use this :

TelephonyManager tm = (TelephonyManager) getSystemService(android.content.Context.TELEPHONY_SERVICE);

EDIT : *you should pass the context to your new Class on the constructor :*

public class YourClass {
    private Context context;

    //the constructor 
    public YourClass( Context _context){

        this.context = _context;
        //other initialisations .....

    }

   //here is your method to get the IMEI Number by using the Context that you passed to your class
   public String getIMEINumber(){
       //...... place your code here 
   }

}

And in your Activity , instanciate your class and pass the context to it like this :

YourClass instance = new YourClass(this);
String IMEI = instance.getIMEINumber();