首页 > 解决方案 > Firebase 身份验证 - 我在获得 onCodeSent 后获得 onVerificationCompleted 回调 3s

问题描述

在一台设备上,当我尝试使用电话号码在 Android 上通过 Firebase 进行身份验证时,我收到两个回调 - onCodeSent,然后 3 秒后,onVerificationCompleted。我的代码:

fun verifyPhone(
    phoneNumber: String,
    activity: Activity,
    authCallbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks
) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
        phoneNumber,
        AUTH_TIMEOUT_SEC,
        TimeUnit.SECONDS,
        activity,
        authCallbacks
    )
}

authCallbacks 如下所述:https ://firebase.google.com/docs/auth/android/phone-auth

到目前为止,仅在一台设备上发现了该问题-其他设备根本没有发现onVerificationCompleted-仅 onCodeSent。

 2020-12-03 18:45:56.343 2820-2820/com.project.name
 D/EnterPhoneViewModel$authCallbacks: onCodeSent
 2020-12-03 18:45:59.232 2820-2820/com.project.name
 D/EnterPhoneViewModel$authCallbacks: onVerificationCompleted

回调之间没有其他用户或程序操作,除了切换到用户等待 SMS 代码的新片段。请注意,回调来自同一个 ViewModel,即使由于接收 onCodeSent 我已经转移到另一个片段(和它自己的 ViewModel)。这会打乱执行流程,偶尔会导致我的代码崩溃。应该像这样调用回调吗?如果是这样,那么我想一种处理方法是也从 EnterCodeFragment 访问 EnterPhoneViewModel。

标签: androidfirebase-authentication

解决方案


这很可能是由于代码被自动验证。从发送验证码的 Firebase 文档中:

mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {    
   @Override
   public void onVerificationCompleted(PhoneAuthCredential credential) {
       // This callback will be invoked in two situations:
       // 1 - Instant verification. In some cases the phone number can be instantly
       //     verified without needing to send or enter a verification code.
       // 2 - Auto-retrieval. On some devices Google Play services can automatically
       //     detect the incoming verification SMS and perform verification without
       //     user action.
       Log.d(TAG, "onVerificationCompleted:" + credential);

       signInWithPhoneAuthCredential(credential);
   }

如此重复以强调:

在某些设备上,Google Play 服务可以自动检测传入的验证短信并执行验证,无需用户操作。

无法保证该功能适用​​于所有具有 Google Play 服务的设备,但如果它有效,它会阻止用户手动查找并输入代码。


推荐阅读