Sunday, October 3, 2010

How to get IMEI on Android Devices?

Hi Readers,

As per your queries about IMEI on Android devices; I am posting this article, please do let me know with your feedback and further queries. The solution is as follows:-

Device, network, SIM & data state related info on Android platform is managed by TelephonyManager. Your application can use the methods defined in this class to determine the desired information. Please note, you cannot instantiate this class directly; instead you need to retrieve a reference to an instance like this:-

String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);

To access some telephony information you need to set appropriate permission in your application manifest file, because few informations are permission protected. In our case we need to set permission for our app:-

Now let's start with actual source code to retrieve the information:-

public String findDeviceID() {
     String deviceID = null;
     String serviceName = Context.TELEPHONY_SERVICE;
     TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
     int deviceType = m_telephonyManager.getPhoneType();
     switch (deviceType) {
           case (TelephonyManager.PHONE_TYPE_GSM):
  case (TelephonyManager.PHONE_TYPE_CDMA):
  case (TelephonyManager.PHONE_TYPE_NONE):
     deviceID = m_telephonyManager.getDeviceId();
     return deviceID;

The above method will return you the IMEI in-case of GSM and MEID or ESN for CDMA devices. When you can run this code on real device the output will be like this:-
Point to be noted here is deviceType that we are getting using TelephonyManager Class. This code will work on Android 1.6 and above because CDMA stack is implemented on Android 1.6 and above. So If you are using Android 1.5 devices just remove CDMA related code from it.

Using TelephonyManager you can retrieve much more information about device. For example:-

Retreive MSISDN:-
String msisdn =  m_telephonyManager.getLine1Number();
Retreive SIM Serial Number:-
String simSerialNumber = m_telephonyManager.getSimSerialNumber();
Retreive IMSI:-
String imsi = m_telephonyManager.getSubscriberId();

For more info please visit TelephonyManager