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

TL;DR

  • 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 http://console.firebase.google.com/ 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. MainActivity.java 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 ProfileActivity.java.
  • If the user is not logging in, ask them to include a phone number to log in.
2. VerifyPhoneActivity
  • VerifyPhoneActivity.java 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
  • ProfileActivity.java 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 MainActivity.java.

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);
            startActivity(intent);
            finish();
}

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="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">
        
        <!--  TextView asking for phone number -->
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="168dp"
            android:text="May I ask your phone number?"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline"
            android:textColor="@color/colorPrimary"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.367"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
 
        <!--  EditText where user can write phone number-->
        <EditText
            android:id="@+id/editTextMobile"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="32dp"
            android:layout_marginTop="284dp"
            android:digits="0123456789"
            android:hint="enter your mobile number"
            android:inputType="phone"
            android:maxLength="12"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.25"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/textView" />
 
        <!--  Button to continue the process -->
        <Button
            android:id="@+id/buttonContinue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="324dp"
            android:background="@color/colorPrimaryDark"
            android:text="Continue"
            android:textAllCaps="false"
            android:textColor="#cdd8f1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.498"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
 
    </androidx.constraintlayout.widget.ConstraintLayout>

And we got to get the telephone number from that EditText in MainActivity.java 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) {
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                    "+" + 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() {
            @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();
                Log.i(TAG, "onVerificationFailed: " + e.getLocalizedMessage());
            }
 
            //when the code is generated then this method will receive the code.
            @Override
            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);
            signInWithPhoneAuthCredential(credential);
        }

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) {
    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 = "Something is wrong, we will fix it soon...";

                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                    message = "Invalid code entered...";
                }
                Toast.makeText(VerifyPhoneActivity.this,message,Toast.LENGTH_SHORT).show();
            }
        }
    });
}

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() {
    @Override
    public void onClick(View v) {
 
        firebaseAuth.signOut();
        Intent intent = new Intent(ProfileActivity.this,MainActivity.class);
        startActivity(intent);
    }
});

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

Post a Comment

Previous Post Next Post