Welcome folks I am back with another blog post. In this post we will be implementing Firebase Phone Authentication in Android from scratch. Phone Authentication is a modern way of letting users sign in our app. It removes the hassle of signing up of email id and confirming that email address. It also increases the engagement level of the app as users don’t have to left the app to register with it. They can simply use their phone to sign up for your app. So phone authentication is more popular these days in all sort of apps. We will be implementing in our demo app to get started with it. Let’s start the journey.

So the No 1 step is to open Android Studio and create a brand new Project by clicking the start a new project option in the interface.

After opening Android studio and tapping on the Start a new Android Studio Project give a name for your Project and then click next to select the activity of your project.

After you have named your project and click next you will granted with this screen in which you have to select the appropriate activity of your project. For this moment of time we are selecting the empty activity as this is a simple App. So select empty activity. And then click next two more times and after that project will build it may take some time depending on your internet speed and computer speed.

So after building your project you have to connect your project to Firebase. In order to connect your project to Firebase two approaches are there first is manual and second one is automatic we will follow the automatic and much easier approach here as it’s also the recommended one. We will connect project to Firebase using the Firebase Assistant that is available in Android Studio. Go to Tools and select Firebase and follow the steps listed above

After selecting Firebase under the Tools you will be granted with the Firebase Assistant in which you have to select Email and Password Authentication in order to setup Authentication for your Android project.

After selecting email and password authentication you have to connect your app to Firebase by tapping the button of Connect to Firebase as shown in the figure below.

Just click on the button of Connect to Firebase and then the gradle will connect your project to Firebase in the background and also you will be granted with the screen of selecting the project to connect to Firebase or create a new one . Just click next and gradle will do the rest for you.

After selecting the project just click next to connect the project to Firebase and wait for sometime as it depends on your internet connection and pc speed. If any error comes likes this shown below just press sync anyway to continue the process again and then it will connect successfully.

After clicking the Sync button it will connect your project to firebase successfully and should see the green light appearing on the connect to firebase button something like this as shown below.

After you have successfully connected to firebase just click the below button to add firebase authentication component to your app and after that it will also have green light appearing something like this as shown below.

After all this your project has been successfully connected to firebase and has the authentication component also connected. After the gradle finishes sometimes some users may get an error something like this as shown below.

To counter this error just go to the top level build.gradle file of your android project and then change google play services version from 3.1.1 to 3.2.0.

Just change the version of the Google Player Services from 3.1.1 to 3.2.0. If you do that and sync the changes then the error will gone.

After that you have to enable Phone Authentication in the Firebase console. Just go the firebase console select your project and set up the sign-in method. In this case the sign-in method if Phone Auth so enable it

Click the set up sign-in method and choose the Phone Auth and enable it and save the changes to take effect on the project.

After enabling it just click save button it will save the changes to the project. You are done enabling Phone Auth in Firebase Console.

Now the Fun part begins i.e. the coding part first of all we will be making the interface of the application by editing then xml part. Go to the activity_main.xml file and copy paste the source code shown below.

<?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"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter you Phone Number"/> <EditText android:id="@+id/mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Continue"/> </LinearLayout> </RelativeLayout>

After you have copy pasted this code in activity_main.xml file you have successfully created the interface of the main activity of the application. Let’s see the figure as shown below.

So as you can see in the figure we have a text field in which you can enter the mobile number from which you want to register in the application. After that we have the continue button which you will press to get into the verification activity of the mobile number that you have entered i.e. an otp code will be sent to the mobile number and after that you will be successfully signed in to the app.

After making the interface of the main activity we will be making the interface of the verify number activity in which we will be verifying the mobile number by sending the otp number to that number. Make a new Activity VerifyNumber Activity and copy paste the code into activity_verify_mobile.xml file to make the interface.

<?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=".VerifyMobile"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter the OTP Code sent to your Mobile"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:id="@+id/otp"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/login" android:text="Login"/> </LinearLayout> </RelativeLayout>

After making the OTP Code Verification Activity the last activity that we want to make is the simple profile Activity which we will be redirecting users when they are successfully registered into the app. Make a new activity called ProfileActivity and copy paste the xml code into the activity_profile.xml file.

<?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=".ProfileActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome Buddy to the App" android:textSize="25sp" android:textStyle="bold"/> </RelativeLayout>

This wraps all of the xml code of the project. The interface part of the application is complete so now we want to focus on the business logic of the android app i.e. Java code so go back to the activity_main.java file and write some code as shown below.

Related Posts

package com.codingshiksha.firebasephoneauth; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText mobile; Button button; String no; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mobile = (EditText) findViewById(R.id.mobile); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { no = mobile.getText().toString(); validNo(no); Intent intent = new Intent(MainActivity.this,VerifyMobile.class); intent.putExtra("mobile",no); startActivity(intent); Toast.makeText(MainActivity.this,no,Toast.LENGTH_LONG).show(); } }); } private void validNo(String no){ if(no.isEmpty() || no.length() < 10){ mobile.setError("Enter a valid mobile"); mobile.requestFocus(); return; } } } This is the whole code of the main activity. I will break it down into various sections and I will give explanation of each section. Let’s start with the first section of code in the app. EditText mobile; Button button; String no; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mobile = (EditText) findViewById(R.id.mobile); button = (Button) findViewById(R.id.button); This is the first section of code in the main activity java file. In this section we are just initializing some instance variables which we have declared in the xml file. There is one edittext field in which we will be entering the mobile number to verify and a button to continue the process of verification. So very simple method is used i.e. findviewbyid. button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { no = mobile.getText().toString(); validNo(no); Intent intent = new Intent(MainActivity.this,VerifyMobile.class); intent.putExtra("mobile",no); startActivity(intent); Toast.makeText(MainActivity.this,no,Toast.LENGTH_LONG).show(); } }); } private void validNo(String no){ if(no.isEmpty() || no.length() < 10){ mobile.setError("Enter a valid mobile"); mobile.requestFocus(); return; } } }

This is the second section of the code of the main activity java file. In this code we are firstly validating the mobile number that the user has entered into the text field. We are firstly checking if the number is empty or either the number length is smaller than 10 if either it is the case we are not moving forward. And secondly we are binding an onevent click listener on the button element so that whenever the button has been clicked we are passing the mobile number to another activity by using intents and then we are moving to the second activity i.e. VerifiyMobile Activity to verify the number.

After this we will going to the VerifyMobile Activity to verify the mobile number that the user has entered so let’s look at the whole code of this activity to get the gist of the whole code. And then we will take each section of the code and go through each section.

package com.codingshiksha.firebasephoneauth; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; 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 VerifyMobile extends AppCompatActivity { EditText otp; Button login; String no; private FirebaseAuth mAuth; private String mVerificationId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verify_mobile); otp = (EditText) findViewById(R.id.otp); mAuth = FirebaseAuth.getInstance(); no = getIntent().getStringExtra("mobile"); sendVerificationCode(no); login = (Button) findViewById(R.id.login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String code = otp.getText().toString().trim(); if (code.isEmpty() || code.length() < 6) { otp.setError("Enter valid code"); otp.requestFocus(); return; } //verifying the code entered manually verifyVerificationCode(code); } }); } private void sendVerificationCode(String no) { PhoneAuthProvider.getInstance().verifyPhoneNumber( "+91" + no, 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) { otp.setText(code); //verifying the code verifyVerificationCode(code); } } @Override public void onVerificationFailed(FirebaseException e) { Toast.makeText(VerifyMobile.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(VerifyMobile.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(VerifyMobile.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..."; } } } }); } }

In the first section of the code we are just declaring some instance variables that we have declared in the xml file. There is one edittext field and one button and a string variable to hold the actual mobile number and apart from that we are declaring two variables of type firebaseauth for the firebase authentication and a unique verification id variable of type string which will be useful to identify the user in case the otp is send to the mobile number. Let’s see the code in action as shown below.

EditText otp; Button login; String no; private FirebaseAuth mAuth; private String mVerificationId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verify_mobile); otp = (EditText) findViewById(R.id.otp); mAuth = FirebaseAuth.getInstance(); no = getIntent().getStringExtra("mobile"); sendVerificationCode(no); login = (Button) findViewById(R.id.login);

In the second section of the code as shown below we can see that we are making a custom function to send the verification code to the user mobile number to verify the user that he/she is a valid user or not for this purpose we are using an inbuilt method verifyPhoneNumber of PhoneAuthProvider to send the code it takes five arguments in its method first is the actual number where to send the code and second is the time period in which the sms will be sent in this case 60 seconds are passed thirdly timeunit is specified in this case seconds are specified. Last two parameters signify on which thread you want to run this process so in this case main thread will be passed and secondly the callback function to be executed after the code has been sent to the user mobile number so in this callback function we can verify the user if the user has received the code and the entered code is valid or not.

private void sendVerificationCode(String no) { PhoneAuthProvider.getInstance().verifyPhoneNumber( "+91" + no, 60, TimeUnit.SECONDS, TaskExecutors.MAIN_THREAD, mCallbacks); }

In this section of code as shown below we are implementing the callback function which we have passed in the sendverificationcode function i.e. the last parameter this function will execute as soon as the code is sent to the user mobile number. Firstly here we are overriding some methods of this inbuilt interface firstly OnVerificationCompleted i.e function responsible when the code has been successfully sent to the user mobile. In this function first of all we are grabing the sms code and then we are checking if the code is not equal to null in that scenario the user will have to manually enter the code that is sent to the mobile. After that we will be verifying the code entered by the user if the code is valid or not. If the code is valid then we will grant access to the user to the ProfileActivity else not. Apart from that there are also two additional methods there in this interface that needs to be implemented firstly the method responsible when the code has failed to send and secondly when the code has reached the mobile phone instantly this second function will execute so in this function we will grab the verificationid of the user and this verificationid we will use later in the verification function to verify the code entered by the user.

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) { otp.setText(code); //verifying the code verifyVerificationCode(code); } } @Override public void onVerificationFailed(FirebaseException e) { Toast.makeText(VerifyMobile.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; } };

So in this section of code as shown below we are just making the custom function of verifying whether the code entered by the user is correct or not. In this function firstly we are making the PhoneCredential object which stores the credential of the user in the form of VerificationId and the actual code which is received on the mobile phone. This credential object is passed to another custom function which we will create in the next step to authenticate the user with firebase. So you can say that all the boilerplate code of authentication lies in this sole function.

private void verifyVerificationCode(String code) { //creating the credential PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code); //signing the user signInWithPhoneAuthCredential(credential); }

So this is the last and the main section of the code in which we are really implementing the authentication part of this app. In this function we are first of all passing the PhoneCrendential object so that the function can use it. There is only inbuilt function used i.e. signInWithCredential and passing the credential object as an argument so this function also have callback for successfull completion and also has a callback in case the function doesn’t execute successfully. In the successfull completion we know that the user is authenticated so we redirect the user to the profile Activity. And in case the the function gives error then we know that something has gone wrong so we can grant the user with the message that wrong code entered please try again.

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(VerifyMobile.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(VerifyMobile.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..."; } } } }); }

Congratulations we are done making the Firebase Phone Authentication in Android from scratch. All the source code of the Application is available below to download. Thanks for reading this post and if you like reading this and wants to read more of this please subscribe the blog below to get all the notications.