How to Use Firebase to Sign Up/Sign In With A Phone Number

Do you want your users to register with a phone number when they download your app?

It means that your users will sign in and sign on with a mere signaling rather than email which may be sophisticated to several users.

Firebase to Sign Up

I know it’s an amazing feature you'll be able to get victimization base in automaton Studio.

You might be brooding about however it’s potential. base authentication SDK is capable of providing this sturdy feature.

You can conjointly investigate the opposite ways in which I delineated in details,

  • Signup user with Email And word victimization base Authentication
  • Login with Google victimization base Authentication in robot


  • You can collect associate authentic number type the user.
  • If you're using a secure payment app, generate an OTP (one-time password).
  • You can fully register a user using only his or her phone number [no need for an email address].

Using a Phone Number to Authenticate with Firebase

Without any more due, let’s get straight into secret writing & development.

Step 1 – Open Android Studio and Create a New Project

Create a new project by clicking on File -> New -> New Project

Step 2 – Connect the App to the Firebase Cloud Platform

  • Once the project is formed, you would like to feature base AUTH to your project.
  • Click on Tools –> base it'll open a replacement window on the correct aspect within which you'll be able to see all the services that square measure provided by base.
Firebase assistant
  • As we have a tendency to have an interest in base of operations Authentication solely, thus we'll select that. Click on Authentication -> Email and password Authentication.
Email password auth
  • Before adding the base of operations Authentication dependencies to our robot app, we want to initial hook up with base of operations. Click on connect to firebase.
Connect To Firebase

If you're not logged into to automaton Studio exploitation your Google account then it'll raise you to log in, otherwise, it'll show you windows to decide on or existing firebase project or produce a brand new one

I am making a brand new firebase Project thus I will enter the project name, choose Country and click on connect with firebase.

New Firebase project

That’s it, our app is currently connected to firebase.

Step 3 – Add Authentication to Your Project Using Firebase

1. It’s straightforward as before, simply click the button voice communication Add firebase Authentication to your app.

Apply changes

2. Click Apply Changes, once a while you'll be able to see all the dependencies created properly.

Step 4 – In the Firebase Console, change the registration to include a phone number.

Go to and login to with identical ID that's logged in to robot Studio.

As you can see, our project was successfully added. Now simply click on it.

Console project
  • From the left pane, choose Authentication.
  • Toggle over to the Sign-in technique tab.
  • Activate the phone by selecting it and clicking the toggle button.
Enable Phone Authentication

And firebase work is finished. now's the time that we tend to begin writing code in mechanical man Studio.

Step 5: Structuring the applying

The application contains 3 activities:

1. MainActivity
  • This may be the primary operation, which will be dead once the user launches the app. with activity main.xml layout files; this may be the primary activity, which will be dead once the user launches the app.
  • But we want to see if any users are still logging in, and if they are, we want to send them to
  • If the user is not logging in, ask them to include a phone number to log in.
2. VerifyPhoneActivity
  • with activity_verify_phone.xml layout file; it'll be dead once the user has provided the range|telephone number|number|signal|signaling|sign} and verification code has been sent to it number.
  • So it'll be asking the user to supply that verification code to finish the sign-in method.
3. ProfileActivity
  • with activity profile.xml layout files; once the user logs in, this activity will be deactivated.
  • As a result, it will be in charge of displaying the welcome message and conducting the Logout Operation.
So please plow ahead and make these 3 activities in mechanical man Studio, so we are able to begin cryptography every of them.

Coding the Application

Here is that the cryptography half.

A. Checking If somebody Already Logged In?

The awfully first thing we'd like to do – as soon as the app launches – is check to see whether someone is still signed in or not.

As the MainActivity are going to be dead at the terribly begin therefore we have a tendency to code it in

So if somebody logged in then airt them Associate in Nursingother|to a different} activity wherever their profile are going to be shown together with an choice to sign out, otherwise, allow them to give the sign to sign on.

We can check the present user with associate degree instance of FirebaseAuth:

//check whether the user is logged in
        if (currentUser != null) {
            //if logged in the start the Profile activity
            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);

B. obtaining the sign from Users

If not logged in then we want to prompt the user to supply a sign and perform the login.

And for that we tend to need:
  1. A TextView asking the user to supply their sign
  2. An EditText to urge that sign
  3. A Button to perform that operation
We produce these 3 things within our activity_main.xml as a result of that's answerable for it.

Here is that the complete code of activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android=""
        <!--  TextView asking for phone number -->
            android:text="May I ask your phone number?"
            app:layout_constraintTop_toTopOf="parent" />
        <!--  EditText where user can write phone number-->
            android:hint="enter your mobile number"
            app:layout_constraintTop_toBottomOf="@id/textView" />
        <!--  Button to continue the process -->
            app:layout_constraintTop_toTopOf="parent" />

And we got to get the telephone number from that EditText in once the Continue button is clicked.

We all savvy to do do} that; making an instance of EditText, then initializing it victimization findViewById and providing the ID. so career .getText().toString() functions. That’s pretty straightforward and straight-forward, therefore i'll not be explaining that physical object here cause it'll get this text too long.

C. Causing Verification Code

Once we've got the number – and in fact when activity the little checks like if the number is valid, not empty, etc – we want to send a verification code from base.

There is a way named verifyPhoneNumber() that we are able to decision and supply the relevant argument and it'll send a verification code to the number we have a tendency to provided. Here is how:

//The procedure entails submitting a verification code.
//Concatenation of country identifiers.
//You may also use the country id as a user input.
        private void sendVerificationCode(String mobile) {
                    "+" + mobile,                 //phoneNo that is given by user
                    60,                             //Timeout Duration
                    TimeUnit.SECONDS,                   //Unit of Timeout
                    TaskExecutors.MAIN_THREAD,          //Work done on main Thread
                    mCallbacks);                       // OnVerificationStateChangedCallbacks

D. Handling the Callbacks

The higher than technique can send the verification code to produce variety, however we'd like to stay track of this operation and within the finish, we tend to conjointly got to verify it.

And for those, verify the last argument mCallbacks. we'd like to produce associate degree instance of PhoneAuthProvider.OnVerificationStateChangedCallbacks category to handle the recall functions.

We can override the recall strategies like onVerificationCompleted, onVerificationFailed and onCodeSent.
  • onVerificationCompleted technique are going to be known as in 2 things (basically once the verification has been completed)
    • a. Instant Verification, in some cases telephone number are often instantly verified while not having to send or enter a verification code.
    • b. Auto-retrieval. On some devices, Google Play services will mechanically observe the incoming verification SMS and perform verification while not user action.
  • onVerificationFailed technique is termed once one issue went wrong like making degree invalid request (phone selection not valid) or the quota of free SMS has been exceeded.
  • onCodeSent technique is termed once the SMS code has been sent to the provided sign.
Here is however we are going to be handling the callbacks,

//the callback to detect the verification status
        private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =
                new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            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) {
                    //verifying the code
            public void onVerificationFailed(FirebaseException e) {
                Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                Log.i(TAG, "onVerificationFailed: " + e.getLocalizedMessage());
            //when the code is generated then this method will receive the code.
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                //The verification id that is submitted to the user is saved
                mVerificationId = s;
        private void verifyVerificationCode(String code) {
            //creating the credential
            PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code);

E. linguistic communication In with Phone Auth Credentials:

Now the last step is to sign up user mistreatment that phone credentials. This methodology is that the same as sign-in with email and word mistreatment base of operations conjointly having similar asking functions:

//used for signing the user
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
            new OnCompleteListener<AuthResult>() {

        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);

            } else {

                //verification unsuccessful.. display an error message

                String message = "Something is wrong, we will fix it soon...";

                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                    message = "Invalid code entered...";

That’s it, we've got with success logged within the user mistreatment number solely.

Now comes the reverse part:

F. Loggin out the User

As you migh keep in mind, we have a tendency to aforesaid that the ProfileActivity are liable for showing the welcome message and conjointly linguistic communication out the user.

Firebase provided quite easy methodology to perform an indication out the operation; you only got to get the base of operationsAuth instance and decision signOut methodology

So we have a tendency to try this once sign out button is clicked:

firebaseAuth = FirebaseAuth.getInstance();
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(ProfileActivity.this,MainActivity.class);

That’s it. currently you've got an entire understanding of however base Authentication works with sign.

Post a Comment

Previous Post Next Post