How to auto-read OTP in Android programmatically
Auto-reading OTPs (one-time passwords) is a common feature in many Android applications, especially those that require user authentication. This feature can be achieved programmatically by using the SMS Retriever API provided by Google Play Services.
In this article, we'll walk through the steps to auto-read OTPs in Android programmatically using the SMS Retriever API.
Step 1: Add Dependency
First, add the following dependency to your app-level build.gradle file:
?implementation 'com.google.android.gms:play-services-auth:20.4.1'
Step 2: Register Your App
Next, you'll need to register your app with the SMS Retriever API. To do this, add the following code to your app's AndroidManifest.xml file:
<receiver
android:name=".SmsBroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
</intent-filter>
</receiver
Step 3: Implement Broadcast Receiver
Now, implement the SmsBroadcastReceiver class as follows:
领英推è
class SmsBroadcastReceiver : BroadcastReceiver() {
private var listener: SmsListener? = null
fun setListener(listener: SmsListener) {
this.listener = listener
}
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == SMS_RETRIEVED_ACTION) {
val extras = intent.extras
val status = extras?.get(SMS_RETRIEVE_STATUS) as? Status
when (status?.statusCode) {
CommonStatusCodes.SUCCESS -> {
val message = extras.get(SMS_RETRIEVED_MESSAGE) as? String
message?.let { listener?.onSmsReceived(it) }
}
CommonStatusCodes.TIMEOUT -> {
listener?.onSmsTimeOut()
}
}
}
}
interface SmsListener {
fun onSmsReceived(message: String)fun onSmsTimeOut()
}
companion object {
private const val SMS_RETRIEVED_ACTION = "com.google.android.gms.auth.api.phone.SMS_RETRIEVED"
private const val SMS_RETRIEVE_STATUS = "com.google.android.gms.auth.api.phone.EXTRA_STATUS"
private const val SMS_RETRIEVED_MESSAGE = "com.google.android.gms.auth.api.phone.EXTRA_SMS_MESSAGE"
}
}
This code creates a broadcast receiver that listens for incoming SMS messages. When an SMS message is received with the SMS_RETRIEVED action, the onReceive method is called. This method extracts the OTP message from the SMS and passes it to the registered listener.
Step 4: Initiate SMS Retrieval
Now, you can initiate the SMS retrieval process by calling the following method:
private fun startSmsRetriever() {
val client = SmsRetriever.getClient(this /* context */)
val task = client.startSmsRetriever()
task.addOnSuccessListener {
// SMS retrieval started
}
task.addOnFailureListener {
// SMS retrieval failed to start
}
}
This code creates a SmsRetriever client and starts the SMS retrieval process. The addOnSuccessListener and addOnFailureListener methods are used to handle the success and failure cases of the retrieval process.
Finally, we need to register and unregister our broadcast receiver in the onResume and onPause methods of our MainActivity, respectively. Add the following code to your MainActivity:
override fun onResume() {
super.onResume()
val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
registerReceiver(smsBroadcastReceiver, intentFilter)
}
override fun onPause() {
super.onPause()
unregisterReceiver(smsBroadcastReceiver)
}
These methods ensure that our broadcast receiver is registered and unregistered correctly when the activity is resumed and paused, respectively.
That's it! With these steps, you should now be able to auto-read OTP codes in your Android app using the SMS Retriever API.
Shopify Developer | Senior Business Analyst at ENS Enterprises | Supporting and Coaching Brand Building
9 个月I don't have android App. Want to just add this feature if someone open my website in the mobile
Android Software Engineer ??? Peperoncino Evangelist
12 个月Interesting explanation but without the hash of the app this will not work
Final Year | Data Science Enthusiast | Web Development Learner | Actively Pursuing Internship Opportunities
1 å¹´Thanks, that was helpful!
Senior Android Developer | Flutter | Mobile Applications
1 å¹´great work
Software developer, Java|Kotlin|SpringBoot|Android|Kotlin Multiplatform|Angular|Typescript
1 å¹´Well explained, thanks