Authenticate with Firebase on Android (Phone Number) JAVA

MOHD RAZA
2 min readSep 29, 2020

Sign-in for your Firebase project

  1. In the Firebase Console ,Open the Authenticate Section
  2. On the Sign -in-method ,Enable the Phone Number Sign-in-method

Download Source code Link

usually app/build.gradle ADD GRADLE -implementation ‘com.google.firebase:firebase-auth:19.4.0’

Send Verification code to the phone (JAVA)

PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks

Firebase can also be localized by specifying the auth language via the setLanguageCode method -auth.setLanguageCode(“fr”);

When you call PhoneAuthProvider.verifyPhoneNumber, you must also provide an instance of OnVerificationStateChangedCallbacks

mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {

Log.d(TAG, "onVerificationCompleted:" + credential);

signInWithPhoneAuthCredential(credential);
}

@Override
public void onVerificationFailed(FirebaseException e) {
verification is made,

Log.w(TAG, "onVerificationFailed", e);

if (e instanceof FirebaseAuthInvalidCredentialsException) {

} else if (e instanceof FirebaseTooManyRequestsException) {

}
}

@Override
public void onCodeSent(@NonNull String verificationId,
@NonNull PhoneAuthProvider.ForceResendingToken token) {

Log.d(TAG, "onCodeSent:" + verificationId);
mVerificationId = verificationId;
mResendToken = token;
}
};

Sign in the user

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
signed-in user's information
Log.d(TAG, "signInWithCredential:success");

FirebaseUser user = task.getResult().getUser();

}
else
{

Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
invalid
}
}
}
});
}

To sign out a user, call signout

FirebaseAuth.getInstance().signOut();

THANK YOU

--

--