[Android] Automatic OTP Retrieval in Android and JetpackCompose. Also, work on KMM native android part.
Google Play services have two APIs you can use to streamline the SMS-based verification process: 1. SMS Retriever API 2. SMS User Consent API.
In this article, I will cover SMS Retriever API
Prerequisite: To use SMS Retriever API you must have access to customize the OTP message while sending from the server. Because there is a unique hash key for your app that is required to be identified by Google Play services.

Will cover this article in about 7 steps.
Step 1: Generate a Hash key to Format the OTP message Step 2: Adding Gradle Dependencies Step 3: Creating a hint if a device has a sim card and number (Optional) Step 4: Creating SMS broadcast receiver Step 5: Register the broadcast receiver Step 6: Get OTP and unregister the Listener. Step 7: Conclusion
Step 1: Generate a Hash key to Format the OTP message.
First thing first —
We must need to our OTP message like below.
Your <AppName> verification code is 123456
jUwi0GAtiAR
-----------------------
Your GenieInfo verification code is 123456
jUwi0GAtiARIf you look at the message content carefully, the last line has 10 digits hash code. which we need to generate this hash code to retrieve the OTP automatically without granting SMS permission from the user.
If you run the following code in your kotlin project you are able to generate that code.
Note: make sure this hash code is different as per different variants of your project. For debug mode, it will have a different hash code and for release mode, it will have another hash code.
you can use this AppSignetureHelper.kt class anywhare in your project by passing the context of the app. As example —
//TODO: This Helper class need to be delete once ready for production
val context = LocalContext.current
val appSignatureHelper = AppSignatureHelper(context)
Log.e("Atiar OTP Hashkey: ", "key: ${appSignatureHelper.appSignatures}")Once you run the app you will get your HashKey As the first step of Automatic SMS Retrieval in Android. Congrats !!!!!
Tips for testing: You can send an OTP message from your other phone to test. For this just construct the message body with hashCode and send the OTP message as SMS.
Step 2: Adding Gradle Dependencies
Just add the following code to your app level build.gradle.kts file
//SMSRetrieval API Dependencies for Auto OTP Verification
implementation("com.google.android.gms:play-services-auth-api-phone:18.0.1")
implementation("com.google.android.gms:play-services-auth:20.3.0")Step 3: Create a hint if a device has a sim card and number (Optional)
As its an optional item, I'll not go in detail about it. Please follow the official link for more details. https://developers.google.com/identity/phone-number-hint/android
Step 4: Creating SMS broadcast receiver
Our SMS format is ready, and permission added, now it's time to create an SMS Broadcast Receiver to receive the SMS and fill the OTP box automatically.
For this task, we will just create a BroadcastReceiver and that Receiver will automatically catch only our formatted SMS and then we will retrieve the OTP from that SMS content.
Let's check the code for that.
As of the code, you don't need to register the OTP receiver on the AndroidManifest file. We will register it runtime when needed.
Step 5: Register the broadcast receiver
As our Receiver is ready, we will Register the receiver only when we will request to our server for an OTP message. And we will unregisterReceiver when we will receive our OTP .
By the following code you can active the OTPReceiver only when required.
//Here viewModelState.shouldStartSMSRetrival is a state variable,
// and when the state variable will be true the retrival client willl start.
LaunchedEffect(viewModelState.shouldStartSMSRetrival){
launch {
if (viewModelState.shouldStartSMSRetrival){
Log.e("OTP", "SMS Retrieval is Starting...")
startSMSRetrieverClient(context)
}
}
}Note: SMS Retrieval client will be alive for 5min maximum as per google auth SDK.
Step 6: Automatically set OTP to view using Jetpack Compose
As SMS Retrieval started its time to Retrieve the OTP.
val verificationCode = remember { mutableStateOf("") }
LaunchedEffect(1){
val myOTPReceiver = OTPReceiver()
//Registering Broadcast receiver here instead of manifest.
context.registerReceiver(myOTPReceiver, IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION))
//Receiving the OTP
myOTPReceiver.init(object : OTPReceiver.OTPReceiveListener {
override fun onOTPReceived(otp: String?) {
Log.e("OTP ", "OTP Received $otp")
otp?.let { verificationCode.value = it }
// when its true automatically run the function which
// supposed to be run by clicking verify button
// verifyNumberOnClick.value = true
if (myOTPReceiver != null)
context.unregisterReceiver(myOTPReceiver)
}
override fun onOTPTimeOut() {
Log.e("OTP ", "Timeout")
}
})
}As soon as OTP message is received and processed the OTPReceiver will stop listening.
Tips: After starting OTPReceiver if you send an OTP message from another phone it will receive the OTP for you. now you are done.
Step 7: Conclusion
Now you can try Automatic OTP Retrieval on your Native android project or even Kotlin Multiplatform Mobile (KMM)'s Android part.
Happy Coding !!!!
If you have any questions don't hesitate to ask.