大部分安卓手机都可以获取手机唯一码,但是有些手机的厂商却禁止了获取手机唯一码的权限,导致我们不能使用手机唯一码作为标识,但遇到一些必须要填的坑,我们也不能不填,所以使用以下方法来填坑,因此我们使用UUID作为手机的唯一码,虽然不能保证每次都一样,但是基本可以保证唯一
/** * 获取手机唯一标识 * * @return */ public static String getDeviceId() { String deviceId = ConstantUtil.getString(AppConstants.DEVICE_ID); if (StringUtils.isEmptyString(deviceId)) { TelephonyManager TelephonyMgr = (TelephonyManager) BaseApplication.getInstance().getSystemService(TELEPHONY_SERVICE); String id = TelephonyMgr.getDeviceId(); if (StringUtils.isNotEmptyString(id) && !isAllZero(id)) { deviceId = id; } else { deviceId = UUID.randomUUID().toString(); }
// 保存 ConstantUtil.writeString(AppConstants.DEVICE_ID, id); } return deviceId; } public static boolean isAllZero(String str) { Pattern pattern = Pattern.compile("0+"); Matcher matcher = pattern.matcher(str); if (matcher.matches()) { return true; } else { return false; } }