private fun deviceId(): String? {
val deviceIdKey = "makeDeviceID"
val sharedPreferences = getSharedPreferences("AppDate", 0)
var deviceId = sharedPreferences.getString(deviceIdKey, null)
if (deviceId == null) {
deviceId = retrieveDeviceId()
if (deviceId == null) {
deviceId = retrieveAndroidIdOrGenerateUUID()
}
val editor = sharedPreferences.edit()
editor.putString(deviceIdKey, deviceId)
editor.commit()
}
return deviceId
}
private fun retrieveDeviceId(): String? {
return try {
val telephonyManager =
this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (Build.VERSION.SDK_INT < 26) {
telephonyManager.deviceId
} else {
telephonyManager.imei
}
} catch (e: Exception) {
// Handle exception (log if necessary)
null
}
}
private fun retrieveAndroidIdOrGenerateUUID(): String? {
try {
val androidId = Settings.Secure.getString(
this.contentResolver,
Settings.Secure.ANDROID_ID
)
if (androidId != null && androidId.isNotEmpty()) {
return androidId
}
} catch (e: Exception) {
// Handle exception (log if necessary)
}
return UUID.randomUUID().toString().replace("-".toRegex(), "")
}