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

后端 未结 20 2266
滥情空心
滥情空心 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:05

    use below code:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = {Manifest.permission.READ_PHONE_STATE};
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, READ_PHONE_STATE);
            }
        } else {
            try {
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                String imei = telephonyManager.getDeviceId();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    

    And call onRequestPermissionsResult method following code:

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case READ_PHONE_STATE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    try {
                        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        String imei = telephonyManager.getDeviceId();
    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
        }
    }
    

    Add following permission in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    
    0 讨论(0)
  • 2020-11-22 06:06

    to get IMEI (international mobile equipment identifier)

    public String getIMEI(Activity activity) {
        TelephonyManager telephonyManager = (TelephonyManager) activity
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }
    

    to get device unique id

    public String getDeviceUniqueID(Activity activity){
        String device_unique_id = Secure.getString(activity.getContentResolver(),
                Secure.ANDROID_ID);
        return device_unique_id;
    }
    
    0 讨论(0)
提交回复
热议问题