Skip to content

Instantly share code, notes, and snippets.

@rahulsainani
Last active November 17, 2022 09:38
Show Gist options
  • Save rahulsainani/b2ead7f00847cc13a8219b8a4c93c481 to your computer and use it in GitHub Desktop.
Save rahulsainani/b2ead7f00847cc13a8219b8a4c93c481 to your computer and use it in GitHub Desktop.
@Composable
fun SmsRetrieverUserConsentBroadcast(
smsCodeLength: Int = SMS_CODE_LENGTH,
onSmsReceived: (message: String, code: String) -> Unit,
) {
val context = LocalContext.current
var shouldRegisterReceiver by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
Timber.d("Initializing Sms Retriever client")
SmsRetriever.getClient(context)
.startSmsUserConsent(null)
.addOnSuccessListener {
Timber.d("SmsRetriever started successfully")
shouldRegisterReceiver = true
}
}
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it?.resultCode == Activity.RESULT_OK && it.data != null) {
val message: String? = it.data!!.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
message?.let {
Timber.d("Sms received: $message")
val verificationCode = getVerificationCodeFromSms(message, smsCodeLength)
Timber.d("Verification code parsed: $verificationCode")
onSmsReceived(message, verificationCode)
}
shouldRegisterReceiver = false
} else {
Timber.d("Consent denied. User can type OTC manually.")
}
}
if (shouldRegisterReceiver) {
SystemBroadcastReceiver(
systemAction = SmsRetriever.SMS_RETRIEVED_ACTION,
broadCastPermission = SmsRetriever.SEND_PERMISSION,
) { intent ->
if (intent != null && SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
val extras = intent.extras
val smsRetrieverStatus = extras?.get(SmsRetriever.EXTRA_STATUS) as Status
when (smsRetrieverStatus.statusCode) {
CommonStatusCodes.SUCCESS -> {
// Get consent intent
val consentIntent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
try {
// Start activity to show consent dialog to user, activity must be started in
// 5 minutes, otherwise you'll receive another TIMEOUT intent
launcher.launch(consentIntent)
} catch (e: ActivityNotFoundException) {
Timber.e(e, "Activity Not found for SMS consent API")
}
}
CommonStatusCodes.TIMEOUT -> Timber.d("Timeout in sms verification receiver")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment