
Firebase Phone Number Authentication In Android Studio.Hello Guys, Welcome to my new tutorial. Today we will learn how we can implement Phone Number Authentication/Verification using Firebase. Firebase is platform which allow to build web and mobile applications without server side programming language. It provides almost every features ( Authentication,Push Messaging Services,Real Time Database,Storage etc) which we need for our application.
You have seen Phone Number Authentication in most of the application. In which you enter your Phone Number and it send a OTP(One time password) to your number and you need to enter that OTP to authenticate.
Firebase provides simple way to authenticate user by using Phone Number Authentication and yet it is simple to implement. So lets start.
Previously we have already seen how we can implement this feature using Facebook Account Kit. You can check out that tutorial here – Facebook Account Kit SMS Authentication for Android
Firebase Phone Number Authentication In Android Studio – Video Demo
Firebase Phone Number Authentication In Android Studio
Now let’s learn how to implement Firebase Phone Authentication in our project.
Creating Android Project
- Create a new project in Android Studio File–>New–>New Project.
- Enter Application Name, Package Name, Select Empty Activity and click on finish.
Add Firebase To Our Project
- Click on tools -> firebase.
- Connect to Firebase – Click on Connect to Firebase and then you need to choose project you can also create new firebase project and press Connect to Firebase.
- Add Firebase Authentication to your app – Next you need to add gradle to your project. Click “Add Firebase Authentication to your app” and Accept Changes.
- Enable Firebase Phone Authentication –To do this go to Firebase Console and open the project that you are using.Then go to Sign In Method and enable Phone Authentication.
Designing UI (Firebase Phone Number Authentication In Android Studio)
- Now lets Design the User Interface. In our project we will have two activity which are MainActivity and AuthActivity.
- In Main Activity we will check whether user is login or not if he is not we will redirect him to Auth Activity.
- Create AuthActivity.class and activity_auth.xml.
activity_main.xml-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?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="com.androidcodefinder.firebasephonenumberauth.MainActivity"> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="231dp" android:text="logout" app:layout_constraintTop_toTopOf="parent" tools:layout_editor_absoluteX="0dp" /> <TextView android:id="@+id/userPhoneNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/button2" android:layout_centerHorizontal="true" android:layout_marginBottom="105dp" android:text="TextView" /> </RelativeLayout> |
activity_auth.xml-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:background="@color/colorAccent" android:gravity="center_horizontal" android:orientation="vertical" tools:context="com.androidcodefinder.firebasephonenumberauth.AuthActivity"> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" android:fontFamily="sans-serif-condensed" android:text="Firebase Phone Authentication" android:textColor="@android:color/white" android:textSize="25dp" /> <LinearLayout android:id="@+id/phoneLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:background="@drawable/common_google_signin_btn_icon_light_normal_background" android:gravity="center_horizontal" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Step 1" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Verify phone number" android:textColor="@android:color/black" android:textSize="20dp" /> <EditText android:id="@+id/phoneText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:ems="10" android:hint="Phone Number" android:inputType="number" /> <ProgressBar android:id="@+id/phoneBar" style="?android:attr/progressBarStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:visibility="invisible" /> <Button android:id="@+id/sendButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:background="@android:color/holo_blue_dark" android:text="Send Code" android:textColor="@android:color/white" /> </LinearLayout> <LinearLayout android:id="@+id/codeLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:background="@drawable/common_google_signin_btn_icon_light_normal_background" android:gravity="center_horizontal" android:orientation="vertical" android:visibility="gone"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Step 2" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter code sent to your phone" android:textColor="@android:color/black" android:textSize="20dp" /> <EditText android:id="@+id/codeText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:ems="10" android:hint="Enter Code" android:inputType="number" /> <ProgressBar android:id="@+id/codeBar" style="?android:attr/progressBarStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:visibility="invisible" /> <Button android:id="@+id/verifyButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:background="@android:color/holo_blue_dark" android:text="Enter Code" android:textColor="@android:color/white" /> </LinearLayout> </LinearLayout> |
Back End Code
- First let us check whether user is logged In or not.
- In our MainActivity.java first declare an Instance of FirebasAuth.
1 |
private FirebaseAuth mAuth; |
- After that In onCreate() method , initialize the FirebaseAuth instance.
1 |
mAuth = FirebaseAuth.getInstance(); |
- When initializing your Activity, check to see if the user is currently Logged in.If not redirect him to Auth Activity.
1 2 3 4 5 6 7 8 9 10 11 12 |
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser==null){ Intent notLoggedIn = new Intent(MainActivity.this,AuthActivity.class); startActivity(notLoggedIn); finish(); } } |
- We need to add one more function in our this activity which is LOGOUT. We will use Button to logout user.
- Complete code for MainActivity.java is-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.androidcodefinder.firebasephonenumberauth; 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.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class MainActivity extends AppCompatActivity { private FirebaseAuth mAuth; private Button logout; private TextView userPhoneNumber; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); logout = (Button)findViewById(R.id.button2); userPhoneNumber = (TextView)findViewById(R.id.userPhoneNumber); mAuth = FirebaseAuth.getInstance(); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mAuth.signOut(); redirect(); } }); } private void redirect(){ Intent notLoggedIn = new Intent(MainActivity.this,AuthActivity.class); startActivity(notLoggedIn); finish(); } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser==null){ Intent notLoggedIn = new Intent(MainActivity.this,AuthActivity.class); startActivity(notLoggedIn); finish(); } else{ userPhoneNumber.setText("Verified number is- "+FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber()); } } } |
Send a verification code to the user’s phone
- For sending verification code we will use the following code when user will press Send Code button in AuthActivity.java.
1 2 3 4 5 6 |
PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout AuthActivity.this, mCallBacks); |
- mCallbacks: This is our callback that will help us to know the code is sent or not. It has three methods.
- onCodeSent(): This is called when the code is sent successfully. The first parameter here is our verification id that is sent. So we are storing it in our mVerificationId object.
- onVerificationFailed(): This method is called when the verification is failed for some reasons, so here we are only displaying a simple toast.
- onVerificationCompleted(): This method is called when the verification is completed. Here we have the PhoneAuthCredential Object which will give us the code if it is automatically detected
123456789101112131415161718192021222324mCallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {@Overridepublic void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {signInWithPhoneAuthCredential(phoneAuthCredential);}@Overridepublic void onVerificationFailed(FirebaseException e) {Toast.makeText(AuthActivity.this,"error in verification",Toast.LENGTH_LONG).show();}@Overridepublic void onCodeSent(String verificationId,PhoneAuthProvider.ForceResendingToken token) {mVerificationId = verificationId;mResendToken = token;phoneLayout.setVisibility(View.GONE);codeLayout.setVisibility(View.VISIBLE);} - Verifying Code and Sign In – To verify verification code we will use signInWithPhoneAuthCredential() method. If the verification is successful we will let the user sign in into the application.
- Firebase phone authentication have two features if user is using same number on the device it will auto detect the code and verify but if user want to verify other number which he is using on other phone he needs enter manually for that we are using one button.
- Complete code for AuthActivity.java is-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
package com.androidcodefinder.firebasephonenumberauth; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Layout; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import java.util.concurrent.TimeUnit; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; 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.FirebaseUser; import com.google.firebase.auth.PhoneAuthCredential; import com.google.firebase.auth.PhoneAuthProvider; public class AuthActivity extends AppCompatActivity { private EditText phoneText,codeText; private LinearLayout phoneLayout,codeLayout; private ProgressBar phoneBar,codeBar; private Button sendButton,verifyButton; private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks; private FirebaseAuth mAuth; private String mVerificationId; private PhoneAuthProvider.ForceResendingToken mResendToken; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auth); mAuth = FirebaseAuth.getInstance(); phoneText = (EditText)findViewById(R.id.phoneText); codeText = (EditText)findViewById(R.id.codeText); phoneLayout = (LinearLayout) findViewById(R.id.phoneLayout); codeLayout = (LinearLayout) findViewById(R.id.codeLayout); phoneBar = (ProgressBar)findViewById(R.id.phoneBar); codeBar = (ProgressBar)findViewById(R.id.codeBar); sendButton = (Button) findViewById(R.id.sendButton); verifyButton = (Button) findViewById(R.id.verifyButton); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { phoneBar.setVisibility(View.VISIBLE); phoneText.setEnabled(false); sendButton.setEnabled(false); String phoneNumber = phoneText.getText().toString(); PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout AuthActivity.this, mCallBacks); } }); //When you press verify code button verifyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { codeBar.setVisibility(View.VISIBLE); String code = codeText.getText().toString(); PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code); signInWithPhoneAuthCredential(credential); } }); mCallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { signInWithPhoneAuthCredential(phoneAuthCredential); } @Override public void onVerificationFailed(FirebaseException e) { Toast.makeText(AuthActivity.this,"error in verification",Toast.LENGTH_LONG).show(); } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) { mVerificationId = verificationId; mResendToken = token; phoneLayout.setVisibility(View.GONE); codeLayout.setVisibility(View.VISIBLE); } }; } private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information FirebaseUser user = task.getResult().getUser(); Intent LoggedIn = new Intent(AuthActivity.this,MainActivity.class); startActivity(LoggedIn); finish(); // ... } else { // Sign in failed, display a message and update the UI Toast.makeText(AuthActivity.this,"error",Toast.LENGTH_LONG).show(); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid } } } }); } } |
- That’s it now run your application and enjoy.
- I have tried to my best to explain if you have any doubts feel free to comment below or mail me at csesumeet@gmail.com
Firebase Phone Number Authentication In Android Studio
Download Complete Project
Firebase Phone Number Authentication Complete Project
Subscribe To Our YouTube Channel
Like Us On Facebook
Other Tutorials-
- Facebook Account Kit SMS Authentication for Android
- Android Cascading Spinners Using Php Mysql
- Android Upload Image To Server Using PHP MySql
- Dashboard Design In Android Studio Using CardView Tutorial
- Android Build Intro Slider Using ViewPager
- Splash Screen Android
- Login Screen Using LinearLayout
- Awesome Login Screen Design Using Constraint Layout
Sir, Help Me
When I try to run application as shown in your tutorial the application make bug.
And show me RuntimeExcutation Error. I’m mention the hole report in the down :-
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jdgames.aum/com.jdgames.aum.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.jdgames.aum. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.jdgames.aum. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@16.0.4:240)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
at com.jdgames.aum.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:6868)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
… 9 more
This is the hole bug report.
I use all of your codes.
Follow the steps as i did in my blog add “Firebase” direct from your project.