android10之后,获取imei码就不能使用单纯的getDeviceId,因为在android10开始 就已经没有获取IMEI的api了,如果想使用那就直击底层通过映射获取,或者获取别的设备唯一id码,比如android_id。
public static String getIMEIDeviceId(Context context) {
String deviceId;
if (Build.VERSION.SDK_INT >= 29)
{
deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
} else {
final TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return "";
}
}
assert mTelephony != null;
if (mTelephony.getDeviceId() != null)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
deviceId = mTelephony.getImei();
}else {
deviceId = mTelephony.getDeviceId();
}
} else {
deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
}
Log.d("deviceId", deviceId);
return deviceId;
}
补充一下,上述android_id,只能保证本次正常,另外也可以使用设备硬件参数拼接计算出唯一ID
/**
* 获得设备硬件uuid
* 使用硬件信息,计算出一个随机数
*
* @return 设备硬件uuid
*/
private static String getDeviceUUID() {
try {
String dev = "3883756" +
Build.BOARD.length() % 10 +
Build.BRAND.length() % 10 +
Build.DEVICE.length() % 10 +
Build.HARDWARE.length() % 10 +
Build.ID.length() % 10 +
Build.MODEL.length() % 10 +
Build.PRODUCT.length() % 10 +
Build.SERIAL.length() % 10;
return new UUID(dev.hashCode(),
Build.SERIAL.hashCode()).toString();
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}