Firebase Phone number authentication in Android | Android Studio | Java

Golap Gunjan Barman
5 min readMar 29, 2021

Firebase Phone number authentication in Android | Android Studio | Java

In the last of firebase phone number authentication, we design our layout of the phone number login and verification. Now in this tutorial, we’re going to add the functionality of the phone number login and verification.

If you’re not going through the first part of the Firebase Phone Authentication then click here.

Continue for the last part,

in the last part, we set our login button directly to the verification page without any validation of the number. And in the verification page, we do not verify the user using the firebase server and there is no OTP generation.

So in this part, we will add everything on both pages.

Step 1: set up the firebase project

if you don’t know how to set the firebase project, then go through my previous blog on how to set up a firebase project. Click here to know. After setting up the firebase project.

  • Go to the authentication from the left sidebar and click on the get started button.
  • then, go to the sign-in method and enable the phone.

**make sure you’re logged in with the same Gmail account in the android studio, which you logged in with firebase.

Step 2: Login page

On the login page first, we validate the number with the country code picker which will enter by the user. If everything looks good, we will send the user to the verification page.

package com.codewithgolap.youtubetutorials.activities;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.codewithgolap.youtubetutorials.R;
import com.hbb20.CountryCodePicker;
public class LoginActivity extends AppCompatActivity { private CountryCodePicker countryCodePicker;
private EditText number;
Button next;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getWindow().setFlags
(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
countryCodePicker = findViewById(R.id.ccp);
number = findViewById(R.id.editText_carrierNumber);
next = findViewById(R.id.next);
countryCodePicker.registerCarrierNumberEditText(number); next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this,
VerificationActivity.class));
finish();
if (TextUtils.isEmpty(number.getText().toString())) {
Toast.makeText(LoginActivity.this, "Please enter your phone muner",
Toast.LENGTH_SHORT).show();
} else if (number.getText().toString().replace(" ", "").length() != 10) {
Toast.makeText(LoginActivity.this, "Please enter a valid phone number",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(LoginActivity.this, VerificationActivity.class);
intent.putExtra("number", countryCodePicker.getFullNumberWithPlus()
.replace(" ", ""));
startActivity(intent);
finish();
}
}
});
}
}
if (TextUtils.isEmpty(number.getText().toString())) {
Toast.makeText(LoginActivity.this, "Please enter your phone number",
Toast.LENGTH_SHORT).show();
}
  • this if condition checks whether the user enters a number or not, if not then an error toast will show to the user.
if (number.getText().toString().replace(" ", "").length() != 10) {
Toast.makeText(LoginActivity.this, "Please enter a valid phone number",
Toast.LENGTH_SHORT).show();
}
  • this if condition checks whether the user enters a 10 digits number or not, if not then an error toast will show to the user.
else {
Intent intent = new Intent(LoginActivity.this, VerificationActivity.class);
intent.putExtra("number", countryCodePicker.getFullNumberWithPlus()
.replace(" ", ""));
startActivity(intent);
finish();
}
  • else, if everything looks good, we will send the user to the verification activity with the number and the country code picker.

Step 3: Verification Page

now on the verification page, the firebase server first checks the user using ReCaptcha. This is the new feature that is added by the firebase. After verifying the user, firebase will send a 6-digits OTP code to the user.

Then we will check whether the user enters that 6-digits OTP or not ad entered OTP is correct or not.

package com.codewithgolap.youtubetutorials.activities;import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.codewithgolap.youtubetutorials.MainActivity;
import com.codewithgolap.youtubetutorials.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.tuyenmonkey.mkloader.MKLoader;
import java.util.concurrent.TimeUnit;public class VerificationActivity extends AppCompatActivity { private EditText otp;
private Button submit;
private TextView resend;
private MKLoader loader;
private String number, id;
private FirebaseAuth mAuth;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
otp = findViewById(R.id.otp);
submit = findViewById(R.id.submit);
loader = findViewById(R.id.loader);
resend = findViewById(R.id.resend);
mAuth = FirebaseAuth.getInstance();
number = getIntent().getStringExtra("number");
sendVerificationCode(); submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TextUtils.isEmpty(otp.getText().toString())){
Toast.makeText(VerificationActivity.this,
"Enter OTP", Toast.LENGTH_SHORT).show();
}else if (otp.getText().toString().replace(" ",
"").length()!=6){
Toast.makeText(VerificationActivity.this,
"Enter valid OTP", Toast.LENGTH_SHORT).show();
}else {
loader.setVisibility(View.VISIBLE);
PhoneAuthCredential credential = PhoneAuthProvider
.getCredential(id, otp.getText().toString()
.replace(" ",""));
signInWithPhoneAuthCredential(credential);
}
}
});
resend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendVerificationCode();
}
});
} private void sendVerificationCode() {
new CountDownTimer(60000,100){ @Override
public void onTick(long l) {
resend.setText("" + l/1000);
resend.setEnabled(false);
}
@Override
public void onFinish() {
resend.setText(" Resend");
resend.setEnabled(true);
}
}.start();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(number) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(new PhoneAuthProvider
.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted
(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerificationActivity.this,
"Failed!", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String id,
@NonNull PhoneAuthProvider.ForceResendingToken token) {
VerificationActivity.this.id = id;
}
}) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
loader.setVisibility(View.GONE);
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
startActivity(new Intent(VerificationActivity
.this, MainActivity.class));
finish();
FirebaseUser user = task.getResult().getUser();
// Update UI
} else {
// Sign in failed, display a message and update the UI
Toast.makeText(VerificationActivity.this,
"Verification failed! Try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
if (TextUtils.isEmpty(otp.getText().toString())){
Toast.makeText(VerificationActivity.this,
"Enter OTP", Toast.LENGTH_SHORT).show();
}

here we will check whether the user enters an OTP or not.

else if (otp.getText().toString().replace(" ",
"").length()!=6){
Toast.makeText(VerificationActivity.this,
"Enter valid OTP", Toast.LENGTH_SHORT).show();
}

then we will check whether the user enters a valid OTP or not.

else {
loader.setVisibility(View.VISIBLE);
PhoneAuthCredential credential = PhoneAuthProvider
.getCredential(id, otp.getText().toString()
.replace(" ",""));
signInWithPhoneAuthCredential(credential);
}

then if the user enters a valid OTP then we will sign in the user with the phone credentials.

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
loader.setVisibility(View.GONE);
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
startActivity(new Intent(VerificationActivity
.this, MainActivity.class));
finish();
FirebaseUser user = task.getResult().getUser();
// Update UI
} else {
// Sign in failed, display a message and update the UI
Toast.makeText(VerificationActivity.this,
"Verification failed! Try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}

in sign-in phone credential if everything is ok then we will redirect the user to the main activity and if not we will show an error toast message to the user.

Output:

You can follow me on YouTube:

Golap Barman

Also, visit my website for more content like this

www.gbandroidblogs.com

Follow me on Instagram

Android App Developer

Follow me on Facebook

GBAndroidBlogs

--

--

Golap Gunjan Barman

Hi everyone, myself Golap an Android app developer with UI/UX designer.