1. 程式人生 > 程式設計 >Android Q適配之IMEI替換為Android_id

Android Q適配之IMEI替換為Android_id

前置工作:

專案配置升到對應的29版本

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

升級到Android Q後的許可權提示介面

升級到Android Q後的許可權提示介面

老版本獲取IMEI的方法:

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);//獲取Mac地址,在Android 9 P版本中,地址會隨機變化,不可用作唯一標識,可去掉。
      }
    }

    return deviceId;
  }

Android Q獲取IMEI方法

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;
  }

谷歌官方有宣告:手機恢復出廠設定,Android ID會重置。

如果使用者拒絕許可權,也還是會獲取不到裝置標識。

所以具體優化需自行結合開發情景,有更好的建議的道友可以評論補充說明^ - ^…

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。