前置工作:
项目配置升到对应的29版本
compileSdkVersion: 29,
buildToolsVersion: ‘29.0.0',
minSdkVersion : 19,
targetSdkVersion : 29,
javaVersion : JavaVersion.VERSION_1_8
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; }
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会重置。
所以具体优化需自行结合开发情景,有更好的建议的道友可以评论补充说明^ - ^…