How to get the device's IMEI/ESN programmatically in android?

后端 未结 20 2543
滥情空心
滥情空心 2020-11-22 05:19

To identify each devices uniquely I would like to use the IMEI (or ESN number for CDMA devices). How to access this programmatically?

20条回答
  •  无人共我
    2020-11-22 06:04

    The method getDeviceId() of TelephonyManager returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones. Return null if device ID is not available.

    Java Code

    package com.AndroidTelephonyManager;
    
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.telephony.TelephonyManager;
    import android.widget.TextView;
    
    public class AndroidTelephonyManager extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView textDeviceID = (TextView)findViewById(R.id.deviceid);
    
        //retrieve a reference to an instance of TelephonyManager
        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    
        textDeviceID.setText(getDeviceID(telephonyManager));
    
    }
    
    String getDeviceID(TelephonyManager phonyManager){
    
     String id = phonyManager.getDeviceId();
     if (id == null){
      id = "not available";
     }
    
     int phoneType = phonyManager.getPhoneType();
     switch(phoneType){
     case TelephonyManager.PHONE_TYPE_NONE:
      return "NONE: " + id;
    
     case TelephonyManager.PHONE_TYPE_GSM:
      return "GSM: IMEI=" + id;
    
     case TelephonyManager.PHONE_TYPE_CDMA:
      return "CDMA: MEID/ESN=" + id;
    
     /*
      *  for API Level 11 or above
      *  case TelephonyManager.PHONE_TYPE_SIP:
      *   return "SIP";
      */
    
     default:
      return "UNKNOWN: ID=" + id;
     }
    
    }
    }
    

    XML

    
    
    
     
    

    Permission Required READ_PHONE_STATE in manifest file.

提交回复
热议问题