How to auto-read OTP in Android programmatically
https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.uplabs.com%2Fposts%2Fmobile-phone-number-otp-verification-free-ui-kit-screen-design&psig=AOvVaw1TU3NJzjje77CdEKhUQCyh&ust=1678271057740000&source=images&cd=vfe&ved=0CAwQjRxqFwoTCMiztofNyf0CFQAAAAA

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.

Sushma Sharma

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

赞
回复
Giuseppe Scabellone

Android Software Engineer ??? Peperoncino Evangelist

12 个月

Interesting explanation but without the hash of the app this will not work

赞
回复
Aniket Kumar

Final Year | Data Science Enthusiast | Web Development Learner | Actively Pursuing Internship Opportunities

1 å¹´

Thanks, that was helpful!

赞
回复
Ahmed N.

Senior Android Developer | Flutter | Mobile Applications

1 å¹´

great work

赞
回复
Jeremiah Otieno

Software developer, Java|Kotlin|SpringBoot|Android|Kotlin Multiplatform|Angular|Typescript

1 å¹´

Well explained, thanks

赞
回复

要查看或添加评论,请登录

Ali Ahmed的更多文章

  • Understanding the difference between Intent and PendingIntent in Android with examples

    Understanding the difference between Intent and PendingIntent in Android with examples

    Intent Core Purpose: An Intent is a messaging object that expresses your desire to act. It can be used to: Start an…

  • UI Test in Android

    UI Test in Android

    UI testing in Android refers to the process of verifying the functionality and appearance of the User Interface (UI) of…

  • GFDM modulation forms for wireless communication

    GFDM modulation forms for wireless communication

    1. Introduction FDM means dividing the entire frequency band into different smaller frequency bands to be used by…

  • Clickable Custom Calendar - Android

    Clickable Custom Calendar - Android

    Sometimes we need to develop our custom calendar where date cells have to create our-self. So that I develop a calendar…

  • Create ViewPager using RecyclerView?—?Android

    Create ViewPager using RecyclerView?—?Android

    Usually, we use ViewPager for collection sliding views like fragments, images, or any view sections. But today I will…

    4 条评论
  • How to start Android App Development [Basic Guideline]

    How to start Android App Development [Basic Guideline]

    In this article, I will describe how you will start Android app development. You can say that a basic guideline for…

  • Single Touch Image view in Android

    Single Touch Image view in Android

    Small description: When we want to touch a little image, our mental model wants to see that image as big size. In this…

  • Basic Different between Kotlin and Java:

    Basic Different between Kotlin and Java:

    Developed by Kotlin: Kotlin was developed by JetBrains. Andrey Breslav was the team leader of Project Kotlin.

  • How to get SIM number and IMEI number in Android?

    How to get SIM number and IMEI number in Android?

    Step 1: First, in the manifest file have to add a permission which is "READ_PHONE_STATE". This will enable to get…

    1 条评论
  • How to download PDF from byte array or byte stream - Android

    How to download PDF from byte array or byte stream - Android

    We can download easily pdf from byte stream, for that one have to follow some necessary steps. Step 1 : Have to give…

    4 条评论

社区洞察

其他会员也浏览了