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
Since March 28th 2023 in Firebase Android BoM version
31.4.0
(release notes),PhoneAuthOptions.Builder
now accepts a nullActivity
, but it will throw aFirebaseAuthMissingActivityForRecaptchaException
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:Just make sure that you handle the possible
FirebaseAuthMissingActivityForRecaptchaException
error case in theonVerificationFailed
callback as shown in the docs.The API documentation for PhoneAuthOptions.Builder.setActivity says (emphasis mine):
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.