首页 > 解决方案 > Firebase 电话身份验证 OTP 不自动填写 EditText

问题描述

Firebase Phone Authentication 发送的 otp 自动不填写 edittext。otp 是在edittext 中手动输入的。如何自动检测传入的验证短信并通过用户操作执行验证?

otp.kt

private fun sendVerificationCode(phone : String){


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




}

private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks(){
    override fun onVerificationCompleted(p0: PhoneAuthCredential) {

        binding.btnOtpVerify.visible(true)
        binding.progressbarVerify.visible(false)
        val code = p0.smsCode

        if(code != null){
            binding.etOtpView.setText(code)

            VerifyVerificationCode(code)

            signInWithPhoneAuthCredential(p0)
        }
    }

    override fun onVerificationFailed(p0: FirebaseException) {
        binding.btnOtpVerify.visible(true)
        binding.progressbarVerify.visible(false)

        Toast.makeText(this@OtpVerification,p0.message,Toast.LENGTH_LONG).show()
    }

    override fun onCodeSent(p0: String, p1: PhoneAuthProvider.ForceResendingToken) {
        super.onCodeSent(p0, p1)

        binding.btnOtpVerify.visible(true)
        binding.progressbarVerify.visible(false)
        storedVerificationID = p0
        resendingToken = p1


    }

}

标签: androidfirebase-authenticationandroid-edittextone-time-password

解决方案


据我了解,您正在使用 Firebase PhoneAuth 验证电话号码并通过 Firebase 服务器发送 OTP,并且您需要一个工作流来检测包含 OTP 的传入 SMS 并使用此 OTP 自动填充您的 EditText。

要启用自动 OTP 检测,您可以使用 SmsRetriever API 和相关的 SMS User Consent API。

可以在这里找到解释清楚的文档。(包含指向一个参考实现的进一步链接,该实现几乎可以开箱即用,所以我在这里不包括该代码。)

请务必为您的用例选择合适的 API。


推荐阅读