Firebase Phone Authentication Android Tutorial

Firebase Phone Authentication, Today we will find out about Firebase Phone Authentication. Firebase is fantastic, and it offers nearly the functions that you want for the backend of your application. So on this tutorial, we are able to learn about Firebase Phone Authentication, and I am quite certain which you have already seen this element in lots of apps. You enter your telephone number, receives an OTP, and then you definitely use that OTP to authenticate.

Firebase Phone Authentication Video

If you are more cozy in watching video, in which you may see me doing all the stuffs in actual then you could skip this submit and watch the video as a substitute.

<iframe width="560" height="315" src="https://www.youtube.com/embed/JZ8hwzBKsMM" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Benefits of using Phone Authentication

When you use phone variety authentication, you have got many blessings like

  • Preventing Fake Users: When you operate cellphone authentication, the consumer can’t be able to sign up for multiple accounts, as for each account a unique smartphone wide variety is wanted.
  • Increase User Value: When you have got all the customers confirmed with the aid of a smartphone range the fee of your person base increases.
  • Increased Security and User Experience:Nowadays more people using apps and remembering passwords are a headache for many users, in order that they turn out to be the use of susceptible passwords. Using cellphone authentication will increase security and consumer experience, because the user does now not want to create and remember passwords, they will enter their range and then they are able to acquire a transient authentication code by SMS.

Why Firebase Phone Authentication?

For enforcing phone authentication you want to pay for SMS provider, but with firebase, you could do it for FREE, isn’t it extraordinary? The unfastened plan of firebase has Ten Thousand Verification according to month. Thats sufficient for the starter apps I bet, but sure in case you exceed this limit, you need to pay.

So, men sufficient for the discussion now allow’s begin our venture and allow’s see how we are able to integrate cellphone authentication in our software.

Firebase Phone Authentication Tutorial

Now let’s learn how to implement Firebase Phone Authentication in our project.

Creating a new Android Studio Project

  • Again we are able to do it in a brand new mission, so create a new Android Studio project. In my case I actually have created a task named FirebasePhoneAuthentication.
  • Once the assignment is completely loaded, we are able to upload firebase authentication into it.

Adding Firebase Authentication

  • Click on equipment -> firebase. It will open an assistant from in which you could add all the firebase offerings into your task.
  • So from here you could create a brand new firebase project or you can also choose an current challenge.
  • Connect your android undertaking to firebase mission and add the dependencies using this assistant.

If you are confused about this step please follow this Firebase Cloud Messaging Tutorialwhere I explained all the steps about adding firebase to android project.

Enable Firebase Phone Authentication

  • To do that visit Firebase Console and open the challenge which you are the usage of.
  • Then visit Sign In Method and enable Phone Authentication.

Designing Screens

Before stepping into designing I would love to inform you that, for Sign In we are able to have two activities, in the first pastime the consumer will enter his telephone wide variety and in the subsequent we can verify the code sent by means of SMS.

Enter Phone Number Screen

  • I have created this design for this Screen.
  •  
  • For designing the above screen come inside activity_main.xml and write the following xml code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/colorPrimary"
        android:orientation="horizontal">
 
        <ImageView
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:background="@drawable/ic_logo" />
 
    </RelativeLayout>
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_below="@id/relativeLayout"
        android:layout_marginTop="-50dp"
        android:background="@drawable/waves" />
 
    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/imageView"
        android:orientation="vertical"
        android:padding="20dp">
 
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="25dp"
            android:text="May I ask your phone number?"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline"
            android:textColor="@color/colorPrimary" />
 
        <EditText
            android:id="@+id/editTextMobile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/textView"
            android:layout_marginTop="20dp"
            android:digits="0123456789"
            android:drawableLeft="@drawable/ic_phone"
            android:drawablePadding="10dp"
            android:hint="enter your mobile number"
            android:inputType="phone"
            android:maxLength="10" />
 
        <Button
            android:id="@+id/buttonContinue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editTextMobile"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:background="@color/colorPrimaryDark"
            android:text="Continue"
            android:textAllCaps="false"
            android:textColor="#cdd8f1" />
 
    </RelativeLayout>
 
</RelativeLayout>
  • The above xml file will give you some errors as I have used some drawable resources, but don’t worry you can get the resources in my source code and the link of the source code is at the bottom, so keep reading. 

Verify Phone Number Screen

Now we will create the subsequent hobby where we are able to very the smartphone range. In this display as nicely we want an EditText in which consumer will enter the code. But we will discover the SMS routinely so consumer do now not want to enter manually.

  • First create a brand new Activity in the venture, and I have created an hobby named VerifyPhoneActivity.
  • For the above design for your VerifyPhoneActivity, open the activity_verify_phone.xml and write the following xml code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".VerifyPhoneActivity">
 
    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/colorPrimary"
        android:orientation="horizontal">
 
        <ImageView
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:background="@drawable/ic_logo" />
 
    </RelativeLayout>
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_below="@id/relativeLayout"
        android:layout_marginTop="-50dp"
        android:background="@drawable/waves" />
 
    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/imageView"
        android:orientation="vertical"
        android:padding="20dp">
 
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="25dp"
            android:text="Wait for the code I sent You"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline"
            android:textColor="@color/colorPrimary" />
 
        <ProgressBar
            android:id="@+id/progressbar"
            android:layout_below="@id/textView"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
 
        <EditText
            android:id="@+id/editTextCode"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@id/progressbar"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:digits="0123456789"
            android:drawablePadding="10dp"
            android:hint="enter verification code"
            android:inputType="phone"
            android:maxLength="10" />
 
        <Button
            android:id="@+id/buttonSignIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editTextCode"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:background="@color/colorPrimaryDark"
            android:text="Sign In"
            android:textAllCaps="false"
            android:textColor="#cdd8f1" />
 
    </RelativeLayout>
 
</RelativeLayout>
  • Now we will create one more activity named ProfileActivity.

Creating ProfileActivity

  • Create a new EmptyActivity named ProfileActivity and this hobby will open after the successful login.
  • In this screen we’ve not anything but most effective a TextView with a welcome message, as you can see under.

Getting the Mobile Number

  • We will get the cell range of the user in MainActivity. So come inside MainActivity.Java and write the subsequent code.
package net.simplifiedcoding.firebasephoneauthentication;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity {
 
 
    private EditText editTextMobile;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editTextMobile = findViewById(R.id.editTextMobile);
 
        findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                String mobile = editTextMobile.getText().toString().trim();
 
                if(mobile.isEmpty() || mobile.length() < 10){
                    editTextMobile.setError("Enter a valid mobile");
                    editTextMobile.requestFocus();
                    return;
                }
 
                Intent intent = new Intent(MainActivity.this, VerifyPhoneActivity.class);
                intent.putExtra("mobile", mobile);
                startActivity(intent);
            }
        });
    }
 
}
  • The above code may be very sincere. We are simply taking the cell number from EditText and sending it to VerifyPhoneActivity.Magnificence with intent.

Verifying Mobile Number

Sending Verification Code

  • For sending verification code we will use the following code.
private void sendVerificationCode(String mobile) {
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+91" + mobile,
                60,
                TimeUnit.SECONDS,
                TaskExecutors.MAIN_THREAD,
                mCallbacks);
    }
 
 
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
            //Getting the code sent by SMS
            String code = phoneAuthCredential.getSmsCode();
            
            //sometime the code is not detected automatically
            //in this case the code will be null
            //so user has to manually enter the code 
            if (code != null) {
                editTextCode.setText(code);
                //verifying the code
                verifyVerificationCode(code);
            }
        }
 
        @Override
        public void onVerificationFailed(FirebaseException e) {
            Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
 
        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);
            mVerificationId = s;
            mResendToken = forceResendingToken;
        }
    };
  • SendVerificationCode(): This approach will send the verification code. You can also see that I am concatenating +ninety one with the mobile quantity which is the u . S . Code for India. But in actual state of affairs you might have customers from extraordinary international locations. So if that is the case, you need to let the user pick their u . S . As nicely so that you recognise the code, and you may additionally tell the consumer to enter the number with united states of america code.
  • MCallbacks: This is our callback a good way to help us to realize the code is despatched or now not. It has 3 techniques.
  • OnCodeSent(): This is known as whilst the code is despatched successfully. The first parameter right here is our verification id this is despatched. So we are storing it in our mVerificationId object.
  • OnVerificationFailed(): This method is referred to as while the verification is failed for a few reasons, so here we’re simplest displaying a simple toast.
  • OnVerificationCompleted(): This method is known as while the verification is finished. Here we’ve got the PhoneAuthCredential Object with a purpose to deliver us the code if it is mechanically detected.

Verifying Code and Sign In

  • To verify verification code we will use this technique. If the verification is a hit we can permit the consumer sign up into the utility.
private void verifyVerificationCode(String otp) {
        //creating the credential
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, otp);
        
        //signing the user
        signInWithPhoneAuthCredential(credential);
    }
 
    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(VerifyPhoneActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            //verification successful we will start the profile activity
                            Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
 
                        } else {
 
                            //verification unsuccessful.. display an error message
 
                            String message = "Somthing is wrong, we will fix it soon...";
 
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                message = "Invalid code entered...";
                            }
 
                            Snackbar snackbar = Snackbar.make(findViewById(R.id.parent), message, Snackbar.LENGTH_LONG);
                            snackbar.setAction("Dismiss", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
 
                                }
                            });
                            snackbar.show();
                        }
                    }
                });
    }
  • Thats it, it will work. Now let me also show you the full code for VerifyPhoneActivity.java.

VerifyPhoneActivity Code

  • Here is the total code of VerifyPhoneActivity.Java I actually have also written remarks to give an explanation for. But if you have any confusion, you can go away your comment beneath.
package net.simplifiedcoding.firebasephoneauthentication;
 
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
 
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.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
 
import java.util.concurrent.TimeUnit;
 
public class VerifyPhoneActivity extends AppCompatActivity {
 
    //These are the objects needed
    //It is the verification id that will be sent to the user
    private String mVerificationId;
 
    //The edittext to input the code
    private EditText editTextCode;
 
    //firebase auth object
    private FirebaseAuth mAuth;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_phone);
 
        //initializing objects
        mAuth = FirebaseAuth.getInstance();
        editTextCode = findViewById(R.id.editTextCode);
 
 
        //getting mobile number from the previous activity
        //and sending the verification code to the number
        Intent intent = getIntent();
        String mobile = intent.getStringExtra("mobile");
        sendVerificationCode(mobile);
 
 
        //if the automatic sms detection did not work, user can also enter the code manually
        //so adding a click listener to the button
        findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = editTextCode.getText().toString().trim();
                if (code.isEmpty() || code.length() < 6) {
                    editTextCode.setError("Enter valid code");
                    editTextCode.requestFocus();
                    return;
                }
 
                //verifying the code entered manually
                verifyVerificationCode(code);
            }
        });
 
    }
 
    //the method is sending verification code
    //the country id is concatenated
    //you can take the country id as user input as well
    private void sendVerificationCode(String mobile) {
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+91" + mobile,
                60,
                TimeUnit.SECONDS,
                TaskExecutors.MAIN_THREAD,
                mCallbacks);
    }
 
 
    //the callback to detect the verification status
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
 
            //Getting the code sent by SMS
            String code = phoneAuthCredential.getSmsCode();
 
            //sometime the code is not detected automatically
            //in this case the code will be null
            //so user has to manually enter the code
            if (code != null) {
                editTextCode.setText(code);
                //verifying the code
                verifyVerificationCode(code);
            }
        }
 
        @Override
        public void onVerificationFailed(FirebaseException e) {
            Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
 
        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);
 
            //storing the verification id that is sent to the user
            mVerificationId = s;
        }
    };
 
 
    private void verifyVerificationCode(String code) {
        //creating the credential
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code);
 
        //signing the user
        signInWithPhoneAuthCredential(credential);
    }
 
    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(VerifyPhoneActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            //verification successful we will start the profile activity
                            Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
 
                        } else {
 
                            //verification unsuccessful.. display an error message
 
                            String message = "Somthing is wrong, we will fix it soon...";
 
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                message = "Invalid code entered...";
                            }
 
                            Snackbar snackbar = Snackbar.make(findViewById(R.id.parent), message, Snackbar.LENGTH_LONG);
                            snackbar.setAction("Dismiss", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
 
                                }
                            });
                            snackbar.show();
                        }
                    }
                });
    }
 
}
  • Thats it now you can try running your application.

Firebase Phone Authentication Source Code

  • Still having troubles? Don’t fear you can get my source code. Just release the link by using subscribing to my youtube channel.

So that’s excited about this Firebase Phone Authentication Tutorial pals. I wish you found it useful, and if you truly did then please assist me through sharing this put up will all your buddies who are mastering Android Application Development.

And for any question you may depart your remarks here. Thank You