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

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

    You'll need the following permission in your AndroidManifest.xml:

    
    

    To get IMEI (international mobile equipment identifier) and if It is above API level 26 then we get telephonyManager.getImei() as null so for that, we use ANDROID_ID as a Unique Identifier.

     public static String getIMEINumber(@NonNull final Context context)
                throws SecurityException, NullPointerException {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                assert tm != null;
                imei = tm.getImei();
                //this change is for Android 10 as per security concern it will not provide the imei number.
                if (imei == null) {
                    imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
                }
            } else {
                assert tm != null;
                if (tm.getDeviceId() != null && !tm.getDeviceId().equals("000000000000000")) {
                    imei = tm.getDeviceId();
                } else {
                    imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
                }
            }
    
            return imei;
        }
    

提交回复
热议问题