skip to Main Content

I want to use Firebase to authenticate user via phone in an Android app. The doc says to do this

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

The problem is that this exists in Google’s sample project in an Activity class, see relevant file.
I want my app to have MVVM architecture as Google suggests. How to have this in a viewModel class when it needs an Activity context passed in setActivity method? I don’t want any hack that breaks mvvm architecture.

2

Answers


  1. Since March 28th 2023 in Firebase Android BoM version 31.4.0 (release notes), PhoneAuthOptions.Builder now accepts a null Activity, but it will throw a FirebaseAuthMissingActivityForRecaptchaException if app verification falls back to reCAPTCHA. This can happen if Play Integrity is unavailable or if the app fails Play Integrity checks. Therefore, you may now do what the Firebase docs suggest without calling .setActivity(this), like this:

    val options = PhoneAuthOptions.newBuilder(auth)
        .setPhoneNumber(phoneNumber) // Phone number to verify
        .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
        .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
        .build()
    PhoneAuthProvider.verifyPhoneNumber(options)
    

    Just make sure that you handle the possible FirebaseAuthMissingActivityForRecaptchaException error case in the onVerificationFailed callback as shown in the docs.

    Login or Signup to reply.
  2. The API documentation for PhoneAuthOptions.Builder.setActivity says (emphasis mine):

    Sets the Activity to which the callbacks are scoped, and with which app verification will be completed. This is an optional parameter of the builder, but is required to perform a reCAPTCHA fallback for client verification. If the activity is not set and a reCAPTCHA verification is attempted, a FirebaseAuthMissingActivityForRecaptchaException error is thrown, which can be handled in the onVerificationFailed callback.

    So, there is no need to pass an Activity and call setActivity unless you want a reCAPTCHA. If you do need a reCAPTCHA, then you have no choice but to do one of the "hacks" that you’re referring to. A discussion of these hacks has already been done extensively here on Stack Overflow and other places on the internet, and not worth repeating here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search