Search code examples
androidkotlinandroid-jetpack-composebroadcastreceiverone-time-password

how can I send 4 digit sms code to a phone number in compose kotlin?


In jetpack compose kotlin, I want to send a 4-digit sms to the phone number entered by the user, so we can say otp, and I want to read the 4-digit sms I sent and fill in the boxes on the screen automatically, or the user can enter manually, either. But since I've never done anything like this before, I have no idea how to do it. I did a source search but got confused. Could you guide me on this?

Hear is my example screen.

the user will enter her phone on the previous screen and when she presses the button, this screen will appear and a 4-digit sms will be sent to the phone number entered, automatic boxes will be filled or the user will enter it manually.

enter image description here

Hear is my OTPScreen

@Composable
fun VerificationPhoneCodeScreen(
    navHostController: NavHostController,
    state:VerificationPhoneCodeScreenState,
    onChangeOtpValue:(String)->Unit
) {



    Scaffold(
        topBar = {
            BackPopUp(navController = navHostController, route = null)
        },
        backgroundColor = Color.Transparent
    ) {

        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Top
        ) {

            Text(
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(10.dp),
                text = stringResource(id = R.string.telefonuna_gelen_kodu_asagidaki_alana_giriniz),
                style = MaterialTheme.typography.subtitle1
            )

            OtpTextField(
                otpText = state.otpValue,
                onOtpTextChange = { value, otpInputFilled ->
                    onChangeOtpValue(value)
                }
            )
        }
    }
}

Solution

  • There are many approaches to achieve this, can be summarized in the following:

    1. SMS Retriver API which is a Google Play service that allows developers to access SMS messages sent to the device without having to ask for permissions. This API can be used to read SMS messages and verify OTPs automatically. It is a secure and reliable way to authenticate users and protect their data. To use the SMS Retriever API, developers need to register their app with Google Play services. Once registered, the API will automatically detect the OTP message and extract the code from it. The code can then be used to verify the user's identity.

    2. SMS Broadcast Receiver Which is a component of the Android system that listens for incoming SMS messages and broadcasts them to the app. The app can then extract the OTP code from the message and use it to verify the user's identity. To use this method, developers need to register a Broadcast Receiver in their app and specify the SMS message format. The Broadcast Receiver will then listen for incoming messages and extract the OTP code from them, it would be something like this:

    class SMSReceiver : BroadcastReceiver() {
    companion object {
        private val TAG by lazy { SMSReceiver::class.java.simpleName }
    }
    
    override fun onReceive(context: Context?, intent: Intent?) {
        if (!intent?.action.equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) return
        val extractMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent)
        extractMessages.forEach { smsMessage -> Log.v(TAG, smsMessage.displayMessageBody) }
        //TODO
    }
    

    }

    Important Note: You should first provide permission in your manifest and check for it programmatically as it's accessing a sensitive data.

    3. Firebase Firebase is a mobile platform from Google that provides a range of services for developers. It also provides an API that can be used to read SMS and verify OTPs automatically in Android. The API can be used to detect incoming SMS messages and extract the OTP code from them. It also provides additional features such as automatic retry and error handling. Firebase is a great way to simplify the process of reading SMS and verifying OTPs in Android, it would be something like this :

        val options = PhoneAuthOptions.newBuilder(auth)
        .setPhoneNumber(phoneNumber) // Phone number to verify
        .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
        .setActivity(this) // Activity (for callback binding)
        .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
        .build()
    PhoneAuthProvider.verifyPhoneNumber(options)