Firebase phone authentication in android studio 2020 – Part 14

by | Jul 8, 2020 | Android Firebase Tutorials, City Guide App, City Guide Firebase, Database | 0 comments

In this tutorial, we will create firebase OTP authentication in android studio. We will pass data from previous activities which are signup OR forget password. In our previous tutorial we set up firebase in the android studio so, if you are new here then please watch this first.

Watch Youtube tutorial


Firebase OTP Setup

To start the firebase OTP authentication in the android studio we first have to set up the firebase authentication method by first adding the dependency in the project as defined the in here and then we have to Enable the phone number verification in Firebase Console.

Firebase OTP is not working

If your firebase otp is not working then please follow the instructions below. There are few new security policy related items added by Firebase after this tutorial uploaded. So, to use phone authentication we have to follow few new things.

  1. Change the sendVerificationCodeToUser() function as menthioned above by defining varible of mAuth and then initilize it.
  2. Open Build.Gradle (app level)
    1. Update all the dependencies in the app level build.Gradle file
    2. Update the compileSdkVersion to latest (31)
    3. Update the targetSdkVersion to latest (31)
    4. Update the buildToolsVersion to latest (30.0.2)
  3. Now Open Project level Build.Gradle file and update all dependencies in it.
  4. Open Manifest file and set android:exported=”true” in the main <activity> like
    1. <activity android:name=".Common.SplashScreen"
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
  5. Add SHA-256  in the Firebase Console
    1. Open firebase console and select project
    2. Goto Project Settings and scroll to the bottom to add Fingerprints SHA1 and SHA-256
    3. Now to get both fingerprints, open Android Studio
    4. Click on the Gradle from the right most tab
    5. Select your Project and right click on it to see a menu
    6. Select Refresh and you will see Tasks in your project
    7. Open Task -> Android -> and double click on signing report to generate SHA1 and SHA-256 certificates
    8. add them in firebase.
  6. Download latest google-services.json file and add in your project
    1. Select project from the left android studio project menu
    2. Paste the file inside app directory
  7. Add Safety Net
    1. Goto Firebase console -> select app -> settings -> Select App check from the horizontal menu ->
    2. Select on the app and It will open a safety check -> select the agreement checkbox and click add
  8. Clean and rebuild project.

Get data from previous activities

As we call the OTP screen from previous screens so, we have to pass all the data or phone number from called activities like signup or forget a password to perform the phone authentication. So this is the code used to pass data from previous activities using Intent.

Complete phone Number

//Get complete phone number
String _getUserEnteredPhoneNumber = phoneNumber.getEditText().getText().toString().trim(); 
//Remove first zero if entered!
if (_getUserEnteredPhoneNumber.charAt(0) == '0') {
    _getUserEnteredPhoneNumber = _getUserEnteredPhoneNumber.substring(1);
//Complete phone number
final String _phoneNo = "+" + countryCodePicker.getFullNumber() + _getUserEnteredPhoneNumber;

Pass Data From SignUp

Intent intent = new Intent(getApplicationContext(), VerifyOTP.class);

  //Pass all fields to the next activity
                    intent.putExtra("fullName", _fullName);
  intent.putExtra("email", _email);
  intent.putExtra("username", _username);
  intent.putExtra("password", _password);
  intent.putExtra("date", _date);
  intent.putExtra("gender", _gender);
  intent.putExtra("phoneNo", _phoneNo);
  intent.putExtra("whatToDO", "createNewUser"); // This is to identify that which action should OTP perform after verification. 

  //Add Transition
  Pair[] pairs = new Pair[1];
  pairs[0] = new Pair<View, String>(scrollView, "transition_OTP_screen");
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
      ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(SignUp3rdClass.this, pairs);
      startActivity(intent, options.toBundle());
  } else {

Receieve Data in OTP Screen

So we pass the data from previous screen and now we have to receieve it using Intent inside onCreate method.

Get Data

//Get all the data from Intent
        fullName = getIntent().getStringExtra("fullName");
        email = getIntent().getStringExtra("email");
        username = getIntent().getStringExtra("username");
        password = getIntent().getStringExtra("password");
        date = getIntent().getStringExtra("date");
        gender = getIntent().getStringExtra("gender");
        phoneNo = getIntent().getStringExtra("phoneNo");
        whatToDO = getIntent().getStringExtra("whatToDO");

Complete onCreate Method()

PinView pinFromUser;
    String codeBySystem;
    TextView otpDescriptionText;
    String fullName, phoneNo, email, username, password, date, gender, whatToDO;

// [NEWLY Updated code  --  START declare_mAuth]
    private FirebaseAuth mAuth;

    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        pinFromUser = findViewById(;
        otpDescriptionText = findViewById(;

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        //Get all the data from Intent
        fullName = getIntent().getStringExtra("fullName");
        email = getIntent().getStringExtra("email");
        username = getIntent().getStringExtra("username");
        password = getIntent().getStringExtra("password");
        date = getIntent().getStringExtra("date");
        gender = getIntent().getStringExtra("gender");
        phoneNo = getIntent().getStringExtra("phoneNo");
        whatToDO = getIntent().getStringExtra("whatToDO");

        otpDescriptionText.setText("Enter One Time Password Sent Onn"+phoneNo);



Send Verification Code  — [UPDATED]

This is the first function which will be called to send the phone number at user’s provided phone number!

Send Verification COde - LATEST

private void sendVerificationCodeToUser(String phoneNo) {
        // [START start_phone_auth]
        PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth) //mAuth is defined on top
                        .setPhoneNumber(phoneNo)       // Phone number to verify
                        .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
                        .setActivity(this)                 // Activity (for callback binding)
                        .setCallbacks(mCallbacks)          // OnVerificationStateChangedCallbacks
        // [END start_phone_auth]

On Verification State change Callbacks

This is the 2nd function which will be called to check weather auto code send? manual code send or verification failed.

On Verification State Changed CallBacks

private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                    super.onCodeSent(s, forceResendingToken);
                    codeBySystem = s;

                public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
                    String code = phoneAuthCredential.getSmsCode();
                    if (code != null) {

                public void onVerificationFailed(@NonNull FirebaseException e) {
                    Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_SHORT).show();

Verify Code

This is the 3rd function which will be called to execute manual or auto methods and verifying the code send by the system and enter by the user.

On Verification State Changed CallBacks

private void verifyCode(String code) {
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem, code);

Sign In the user

This is the last function which will be called to weather show an error or perform the success message or action defined inside it.

SignIn With Phone Auth Credential

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {

        FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();

                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            //Verification completed successfully here Either
                            // store the data or do whatever desire
                            if (whatToDO.equals("updateData")) {
                            } else if (whatToDO.equals("createNewUser")) {
                        } else {
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                Toast.makeText(VerifyOTP.this, "Verification Not Completed! Try again.", Toast.LENGTH_SHORT).show();

Recommended Posts



City Guide POSTS

City Guide | YouTube Playlist


🚀 Supercharge your Flutter skills! Subscribe to my YouTube channel now for mind-blowing coding insights, expert tips, and exclusive content. Don’t miss out!


Android firebase app - android app 2022 - firebase android app - bulls rent app - coding with t app - android app
android complete login signup product by taimoor sikander free for any type of android app
Flutter E Commerce App Modern and latest
Flutter Login App UI Source Code - Flutter Complete App - Flutter App Design - Flutter App 2023 - Complete Flutter App 2023
Learn flutter from scratch in 4 hours - Flutter Crash Course - Coding with T

Latest Tutorial

How to create a Custom Appbar in flutter. Custom Appbar Design. Flutter App Design
How to create a Custom Shape in Flutter. Flutter E Commerce app Design. Ecommerce app design Flutter. Flutter clippath tutorial
Bottom Navigation bar in Flutter. Flutter Material 3 bottom navigation bar. How to design background color of Flutter bottom navigation bar. Flutter ecommerce app design
Access Admin Panel, Premium Tutorials, Live Chat, 50% off Codes, and More on Patreon!
This is default text for notification bar