Replace IMEI of Android Q with Android_ id

Time:2021-2-25

Front work:

Upgrade the project configuration to the corresponding version 29

compileSdkVersion: 29,
buildToolsVersion: ‘29.0.0′,
minSdkVersion : 19,
targetSdkVersion : 29,
javaVersion : JavaVersion.VERSION_1_8

升级到Android Q后的权限提示界面

Permission prompt interface after upgrading to Android Q

How to get IMEI in the old version:

public static String getIMEI(Context context) {
    String deviceId = null;
    try {
      TelephonyManager tm = (TelephonyManager) context
          .getSystemService(Context.TELEPHONY_SERVICE);
      deviceId = tm.getDeviceId();
      if (deviceId == null || "".equals(deviceId)) {
        return getLocalMacAddress(context);
      }
    } catch (Exception e) {
      e.printStackTrace();
      if (deviceId == null || "".equals(deviceId)) {
        Return getlocalmacaddress (context); // get the MAC address. In Android 9 P, the address will change randomly. It can not be used as a unique ID, but can be removed.
      }
    }

    return deviceId;
  }

How to get IMEI from Android Q


public static String getIMEI(Context context) {
    String deviceId = null;
    try {
      TelephonyManager tm = (TelephonyManager) context
          .getSystemService(Context.TELEPHONY_SERVICE);
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        deviceId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
      } else {
        // request old storage permission
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
          // TODO: Consider calling
          //  ActivityCompat#requestPermissions
          // here to request the missing permissions, and then overriding
          //  public void onRequestPermissionsResult(int requestCode, String[] permissions,
          //                     int[] grantResults)
          // to handle the case where the user grants the permission. See the documentation
          // for ActivityCompat#requestPermissions for more details.
          return null;
        }
        deviceId = tm.getDeviceId();
      }
      if (deviceId == null || "".equals(deviceId)) {
        return getLocalMacAddress(context);
      }
    } catch (Exception e) {
      e.printStackTrace();
      if (deviceId == null || "".equals(deviceId)) {
        return getLocalMacAddress(context);
      }
    }

    return deviceId;
  }

Google official statement: the phone factory settings, Android ID will reset.

If the user refuses the permission, the device ID will still not be obtained.

Therefore, the specific optimization needs to be combined with the development scenario, and Daoyou with better suggestions can comment and supplement ^ – ^

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.