Search code examples
androidfirebase-authenticationone-time-password

how to implemment auto detect otp using firebase?


I have implemented OTP verification using firebase,now I want add auto-detect OTP verification functionality in tha. But before autodetect app should ask about the permission for auto detect. How to do that?


Solution

  • Here You Go

    in gradle

        implementation 'com.google.android.gms:play-services-auth:20.1.0'
        implementation 'com.google.android.gms:play-services-auth-api-phone:18.0.1'
    
    class SMSReceiver : BroadcastReceiver() {
        private var otpListener: OTPReceiveListener? = null
    
        fun setOTPListener(otpListener: OTPReceiveListener?) {
            this.otpListener = otpListener
        }
    
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == SmsRetriever.SMS_RETRIEVED_ACTION) {
                val extras = intent.extras
                val status = extras!![SmsRetriever.EXTRA_STATUS] as Status?
                when (status!!.statusCode) {
                    CommonStatusCodes.SUCCESS -> {
                        val sms = extras[SmsRetriever.EXTRA_SMS_MESSAGE] as String?
                        sms?.let {
                            val p = Pattern.compile("\\d+")
                            val m = p.matcher(it)
                            if (m.find()) {
                                val otp = m.group()
                                if (otpListener != null) {
                                    otpListener!!.onOTPReceived(otp)
                                }
                            }
                        }
                    }
                }
            }
        }
    
        interface OTPReceiveListener {
            fun onOTPReceived(otp: String?)
        }
    }
    

    Manifest

    <receiver
       android:name=".SMSReceiver"
       android:exported="true"
       android:permission="com.google.android.gms.auth.api.phone.permission.SEND">
                <intent-filter>
                    <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
                </intent-filter>
    </receiver>