Last active
September 11, 2020 10:04
-
-
Save alirezanazari/2156ed623511cbae3c580b708830ccc2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SmsReaderUtil @Inject constructor() { | |
private var smsReceiver: SmsReceiver? = null | |
fun register(activity: Activity?) { | |
smsReceiver = SmsReceiver() | |
activity?.let { | |
val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION) | |
activity.registerReceiver(smsReceiver, intentFilter) | |
} | |
} | |
fun setup(activity: Activity?, success: (intent: Intent) -> Unit) { | |
activity?.let { | |
smsReceiver?.success = success | |
try { | |
val client = SmsRetriever.getClient(activity) | |
val task = client?.startSmsUserConsent(NUMBER_OTP_SMS_SERVICE) | |
task?.addOnCanceledListener { | |
log("OTP Retriever Canceled") | |
} | |
task?.addOnFailureListener { | |
log("OTP Retriever Failed ${it.message}") | |
} | |
} catch (e: Exception) { | |
unRegister(activity) | |
} | |
} | |
} | |
fun handleOnResult(data: Intent?, isSixDigit: Boolean, success: (code: String) -> Unit, error: () -> Unit) { | |
val message = data?.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE) | |
if (message != null && message.toLowerCase().contains(SMS_OTP_KEY)) { | |
val code = /** Parse SMS to get Code */ | |
if(code != null) { | |
success.invoke(code) | |
} else { | |
error.invoke() | |
} | |
} | |
} | |
fun unRegister(activity: Activity?) { | |
activity?.let { | |
if (smsReceiver != null) { | |
activity.unregisterReceiver(smsReceiver) | |
smsReceiver = null | |
} | |
} | |
} | |
private fun log(message: String) { | |
if (BuildConfig.DEBUG) Log.e(this.javaClass.name, message) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment