获取具有 Android 版本 8.1 作为 telephonyManager.getDeviceId() 的 phone 的 IMEI 编号;在 Marshmallow 之后被弃用

get the IMEI number of phone having the Android Version 8.1 as the telephonyManager.getDeviceId(); have being deprecated after Marshmallow

@SuppressLint({"MissingPermission", "NewApi"})
public void getDeviceIMEI() {
    String deviceUniqueIdentifier = null;
    String deviceImei = null;
    if (null != telephonyManager) {
        deviceUniqueIdentifier = telephonyManager.getDeviceId();
        Log.d("Output_getDeviceIMEI", deviceUniqueIdentifier + "");
    }
//   

     if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
//            deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
//            Log.d("Output_getDev_null", deviceUniqueIdentifier + "");
//        }

    if (null != telephonyManager) {
        if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            deviceImei = telephonyManager.getImei();
            Log.d("Output_deviceImei_IMEI", deviceImei + "");
        }

    }
    if (null == deviceImei || 0 == deviceImei.length()) {
        deviceImei = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        Log.d("Output_deviceImei", deviceImei + "");
    }

}

从android8开始您需要使用getImei(int slotIndex)获取设备的IMEI。

您还需要在 AndroidManifest.xml

中添加 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 权限

记得在运行时实现权限模型来请求权限,如下所示:

ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    1);
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {

          // If request is cancelled, the result arrays are empty.
          if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

               //continue using `getImei()` or `getDeviceId()`  
            } else {

               //Use device Id or use fallback case
            }
            return;
        }   
    }
}