Skip to content

Instantly share code, notes, and snippets.

@alirezanazari
Last active September 11, 2020 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alirezanazari/2156ed623511cbae3c580b708830ccc2 to your computer and use it in GitHub Desktop.
Save alirezanazari/2156ed623511cbae3c580b708830ccc2 to your computer and use it in GitHub Desktop.
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