Firebase Authentication with Phone Number OTP in Android

13 May, 2022
Many apps require their users to be authenticated. So for the purpose of authenticating the apps uses phone number authentication inside their apps. In phone authentication, the user has to verify his identity with his phone number. Inside the app user has to enter his phone number after that he will receive a verification code on his mobile number. He has to enter that verification code and verify his identity. So this is how phone authentication works. Firebase provides so many ways for authentication users such as Google, Email and Password, Phone, and many more. In this article, we will take a look at the implementation of Phone Authentication inside our App using Firebase. 
We will be creating a simple application which is having two screens. The first screen will be our Verification screen on which the user has to add his phone number. After adding his phone number, the user will click on the Get OTP button after that Firebase will send OTP on that number which is mentioned above. After receiving that OTP user has to enter that OTP in the below text filed and click on the below button to verify with entered OTP. After clicking on the verify button Firebase will verify that OTP and allow the user to enter into the home screen only when entered OTP is correct else the user will get an error message. Note that we are going to implement this project using the Java language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase 
After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Authentication and then email and password authentication. 
After clicking on email and password authentication you will get to see the below screen. Inside this screen click on the first option connect to firebase and after that click on the second option to add Firebase authentication to your app.  
Step 3: Verify that dependency for Firebase authentication is added inside your app
After connecting your app to Firebase. Make sure to add this dependency in your build.gradle file if not added. After adding this dependency sync your project.  
Note: Make sure to add the exact dependency version in the above image because the latest dependency is not having the implementation for auto-detection of OTP. 
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">     <!--Edittext for getting users phone number-->    <EditText        android:id="@+id/idEdtPhoneNumber"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_margin="10dp"        android:hint="Enter your phone"        android:importantForAutofill="no"        android:inputType="phone" />     <!--Button for getting OTP-->    <Button        android:id="@+id/idBtnGetOtp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idEdtPhoneNumber"        android:layout_margin="10dp"        android:text="Get OTP"        android:textAllCaps="false" />         <!--Edittext for getting otp from user-->    <EditText        android:id="@+id/idEdtOtp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idBtnGetOtp"        android:layout_margin="10dp"        android:hint="Enter OTP"        android:importantForAutofill="no"        android:inputType="phone" />     <!--button for verifying user OTP-->    <Button        android:id="@+id/idBtnVerify"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idEdtOtp"        android:layout_margin="10dp"        android:text="Verify OTP"        android:textAllCaps="false" /> </RelativeLayout>
  Step 5: Add permissions for the internet in your Manifest.xml file
Navigate to the app > AndroidManifest.xml file and add the below permissions to it.  
XML
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 6: Create a new Activity for our Home Page 
Navigate to the app > java > your app’s package name > Right-click on your app’s package name and click on New > Activity > Empty Activity and name your activity. Here we have given it a name as HomeActivity.
Step 7: Working with the MainActivity.java file 
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. 
Java
import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.gms.tasks.TaskExecutors;import com.google.firebase.FirebaseException;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.PhoneAuthCredential;import com.google.firebase.auth.PhoneAuthProvider; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity {     // variable for FirebaseAuth class    private FirebaseAuth mAuth;         // variable for our text input    // field for phone and OTP.    private EditText edtPhone, edtOTP;         // buttons for generating OTP and verifying OTP    private Button verifyOTPBtn, generateOTPBtn;         // string for storing our verification ID    private String verificationId;         @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                 // below line is for getting instance        // of our FirebaseAuth.        mAuth = FirebaseAuth.getInstance();                 // initializing variables for button and Edittext.        edtPhone = findViewById(R.id.idEdtPhoneNumber);        edtOTP = findViewById(R.id.idEdtOtp);        verifyOTPBtn = findViewById(R.id.idBtnVerify);        generateOTPBtn = findViewById(R.id.idBtnGetOtp);         // setting onclick listener for generate OTP button.        generateOTPBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // below line is for checking weather the user                // has entered his mobile number or not.                if (TextUtils.isEmpty(edtPhone.getText().toString())) {                    // when mobile number text field is empty                    // displaying a toast message.                    Toast.makeText(MainActivity.this, "Please enter a valid phone number.", Toast.LENGTH_SHORT).show();                } else {                    // if the text field is not empty we are calling our                    // send OTP method for getting OTP from Firebase.                    String phone = "+91" + edtPhone.getText().toString();                    sendVerificationCode(phone);                }            }        });         // initializing on click listener        // for verify otp button        verifyOTPBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // validating if the OTP text field is empty or not.                if (TextUtils.isEmpty(edtOTP.getText().toString())) {                    // if the OTP text field is empty display                    // a message to user to enter OTP                    Toast.makeText(MainActivity.this, "Please enter OTP", Toast.LENGTH_SHORT).show();                } else {                    // if OTP field is not empty calling                    // method to verify the OTP.                    verifyCode(edtOTP.getText().toString());                }            }        });    }     private void signInWithCredential(PhoneAuthCredential credential) {        // inside this method we are checking if        // the code entered is correct or not.        mAuth.signInWithCredential(credential)                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {                    @Override                    public void onComplete(@NonNull Task<AuthResult> task) {                        if (task.isSuccessful()) {                            // if the code is correct and the task is successful                            // we are sending our user to new activity.                            Intent i = new Intent(MainActivity.this, HomeActivity.class);                            startActivity(i);                            finish();                        } else {                            // if the code is not correct then we are                            // displaying an error message to the user.                            Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();                        }                    }                });    }      private void sendVerificationCode(String number) {        // this method is used for getting        // OTP on user phone number.        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(mCallBack)           // OnVerificationStateChangedCallbacks                        .build();        PhoneAuthProvider.verifyPhoneNumber(options);    }     // callback method is called on Phone auth provider.    private PhoneAuthProvider.OnVerificationStateChangedCallbacks                         // initializing our callbacks for on            // verification callback method.            mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {         // below method is used when        // OTP is sent from Firebase        @Override        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {            super.onCodeSent(s, forceResendingToken);            // when we receive the OTP it            // contains a unique id which            // we are storing in our string            // which we have already created.            verificationId = s;        }         // this method is called when user        // receive OTP from Firebase.        @Override        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {            // below line is used for getting OTP code            // which is sent in phone auth credentials.            final String code = phoneAuthCredential.getSmsCode();                         // checking if the code            // is null or not.            if (code != null) {                // if the code is not null then                // we are setting that code to                // our OTP edittext field.                edtOTP.setText(code);                                 // after setting this code                // to OTP edittext field we                // are calling our verifycode method.                verifyCode(code);            }        }         // this method is called when firebase doesn't        // sends our OTP code due to any error or issue.        @Override        public void onVerificationFailed(FirebaseException e) {            // displaying error message with firebase exception.            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();        }    };     // below method is use to verify code from Firebase.    private void verifyCode(String code) {        // below line is used for getting         // credentials from our verification id and code.        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);                 // after getting credential we are        // calling sign in method.        signInWithCredential(credential);    }}
Step 8: Working on HomeActivity
Now we have authenticated our user and move towards our Home Activity. Now we will display a welcome message to our user on successful authentication. For this Navigate to the app > res > layout > activity_home.xml and add the below code to it. 
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".HomeActivity">     <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:padding="10dp"        android:text="Geeks for Geeks \n Welcome to Home Screen"        android:textAlignment="center"        android:textColor="@color/purple_500"        android:textSize="20sp" /> </RelativeLayout>
Step 9: Enable Firebase Phone Authentication in our Firebase Console
For enabling Phone authentication in the Firebase console go to the Firebase Console. Now click on Go to Console option and navigate to your project. After that click on your project. You can get to see the below screen. 
After clicking on Authentication you will get to see the below screen. On this screen click on the Sign-in method tab.
After clicking on Sign in-method you will get to see below list of authentication screens. Click on the Phone option and enable it. 
Click on the Phone option and you will get to see the below pop-up screen. Inside this screen click on the enable option and save it. 
Note: For getting OTP don’t enter your phone number with country code because we are already adding that country code in our code itself. 
Output:
Source: Click here to download the project files.
ruhelaa48
anand00525
sagartomar9927
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.