Introduction

In this article, I am going to explain how to use phone number authentication on Android with Google firebase, which allows users to sign in using their phone number by receiving a One Time Password SMS.

Firebase

Firebase is a backend tool for mobile and web applications.
Google Firebase helps to develop the Application rapidly.
It offers Analytics, Cloud Messaging, Real-time Database, Storage, Remote Configuration, Notification, Crash Reporting, API’s, Multiple Authentication types, Hosting, Dynamic Links and Invites.
Requirements
  • Android Studio.
  • Google Account.
Follow the steps given below to build an Android application
Open an Android Studio and create a new project.
Login to Google Firebase and create a new project in console.
image1
After creating the project select “Add Firebase to your Android app” in Firebase overview page.
image2
After adding an Application, give your Android application package name, App nickname and Debug signing certificate SHA-1 hit REGISTERAPP.
image3
Now, download Google-services.json file add into your application; app folder.
Adding Dependencies
Add the dependencies plug-in in App gradle for firebase phone authentication.
  1. compile 'com.google.firebase:firebase-auth:11.0.4'
Add Gradle plug-in (build.gradle(app)) end of the code.
  1. apply plugin: 'com.google.gms.google-services'
Add classpath plug-in in project gradle
  1. classpath 'com.google.gms:google-services:3.1.0'
Enable Phone Number sign-in for your Firebase project
In the Firebase console, open the Authentication section.
image4
On the Sign-in Method page, enable the Phone Number sign-in method.
Now, go to Android Studio and copy the code.
Creating Layout
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:id="@+id/activity_main"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:orientation="vertical"
  8. android:paddingBottom="@dimen/activity_vertical_margin"
  9. android:paddingLeft="@dimen/activity_horizontal_margin"
  10. android:paddingRight="@dimen/activity_horizontal_margin"
  11. android:paddingTop="@dimen/activity_vertical_margin"
  12. tools:context="io.github.saravanan_selvaraju.phoneauthentication.MainActivity">
  13. <EditText
  14. android:layout_width="match_parent"
  15. android:layout_height="wrap_content"
  16. android:hint="Phone Number"
  17. android:inputType="phone"
  18. android:padding="15dp"
  19. android:maxLength="10"
  20. android:id="@+id/phone"/>
  21. <EditText
  22. android:layout_width="match_parent"
  23. android:layout_height="wrap_content"
  24. android:padding="15dp"
  25. android:id="@+id/code"
  26. android:hint="Verification Code"
  27. android:visibility="gone"/>
  28. <Button
  29. android:layout_width="match_parent"
  30. android:layout_height="wrap_content"
  31. android:text="Verify"
  32. android:layout_below="@+id/phone"
  33. android:id="@+id/getcode"
  34. android:padding="15dp"
  35. android:onClick="GetCode"/>
  36. <Button
  37. android:layout_width="match_parent"
  38. android:layout_height="wrap_content"
  39. android:id="@+id/verify"
  40. android:layout_below="@+id/code"
  41. android:text="Verify"
  42. android:onClick="verify"
  43. android:padding="15dp"
  44. android:visibility="gone"/>
  45. <TextView
  46. android:layout_width="match_parent"
  47. android:layout_height="wrap_content"
  48. android:gravity="center"
  49. android:id="@+id/msgtxt"
  50. android:layout_centerInParent="true"
  51. android:text="Signin Successfully"
  52. android:padding="5dp"
  53. android:textColor="#000000"
  54. android:visibility="gone"/>
  55. </RelativeLayout>
    Creating Activity
    1. package io.github.saravanan_selvaraju.phoneauthentication;
    2. import android.content.Intent;
    3. import android.support.annotation.NonNull;
    4. import android.support.v7.app.AppCompatActivity;
    5. import android.os.Bundle;
    6. import android.util.Log;
    7. import android.view.View;
    8. import android.widget.Button;
    9. import android.widget.EditText;
    10. import android.widget.TextView;
    11. import android.widget.Toast;
    12. import com.google.android.gms.tasks.OnCompleteListener;
    13. import com.google.android.gms.tasks.Task;
    14. import com.google.firebase.FirebaseException;
    15. import com.google.firebase.FirebaseTooManyRequestsException;
    16. import com.google.firebase.auth.*;
    17. import java.util.concurrent.TimeUnit;
    18. public class MainActivity extends AppCompatActivity {
    19. EditText phone,vcode;
    20. TextView msg;
    21. Button getcode,verify;
    22. private FirebaseAuth mAuth;
    23. private String mVerificationId;
    24. private PhoneAuthProvider.ForceResendingToken mResendToken;
    25. private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
    26. @Override
    27. protected void onCreate(Bundle savedInstanceState) {
    28. super.onCreate(savedInstanceState);
    29. setContentView(R.layout.activity_main);
    30. phone = (EditText) findViewById(R.id.phone);
    31. vcode = (EditText) findViewById(R.id.code);
    32. getcode=(Button)findViewById(R.id.getcode);
    33. verify=(Button)findViewById(R.id.verify);
    34. msg=(TextView)findViewById(R.id.msgtxt);
    35. mAuth = FirebaseAuth.getInstance();
    36. mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    37. @Override
    38. public void onVerificationCompleted(PhoneAuthCredential credential) {
    39. Toast.makeText(MainActivity.this,"Verified",Toast.LENGTH_LONG).show();
    40. vcode.setVisibility(View.GONE);
    41. verify.setVisibility(View.GONE);
    42. msg.setVisibility(View.VISIBLE);
    43. }
    44. @Override
    45. public void onVerificationFailed(FirebaseException e) {
    46. Toast.makeText(MainActivity.this,"Login Faled",Toast.LENGTH_LONG).show();
    47. if (e instanceof FirebaseAuthInvalidCredentialsException) {
    48. // Invalid request
    49. // ...
    50. } else if (e instanceof FirebaseTooManyRequestsException) {
    51. // The SMS quota for the project has been exceeded
    52. }
    53. }
    54. @Override
    55. public void onCodeSent(String verificationId,
    56. PhoneAuthProvider.ForceResendingToken token) {
    57. mVerificationId = verificationId;
    58. mResendToken = token;
    59. }
    60. };
    61. }
    62. public void GetCode(View view) {
    63. PhoneAuthProvider.getInstance().verifyPhoneNumber(
    64. phone.getText().toString(),
    65. 60,
    66. TimeUnit.SECONDS,
    67. this,
    68. mCallbacks);
    69. phone.setVisibility(View.GONE);
    70. getcode.setVisibility(View.GONE);
    71. vcode.setVisibility(View.VISIBLE);
    72. verify.setVisibility(View.VISIBLE);
    73. }
    74. public void verfy(View view) {
    75. PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, vcode.getText().toString());
    76. signInWithPhoneAuthCredential(credential);
    77. }
    78. private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    79. mAuth.signInWithCredential(credential)
    80. .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
    81. @Override
    82. public void onComplete(@NonNull Task<AuthResult> task) {
    83. if (task.isSuccessful()) {
    84. vcode.setVisibility(View.GONE);
    85. verify.setVisibility(View.GONE);
    86. msg.setVisibility(View.VISIBLE);
    87. } else {
    88. if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
    89. Toast.makeText(MainActivity.this,"Invslid code",Toast.LENGTH_LONG).show();
    90. }
    91. }
    92. }
    93. });
    94. }
    95. }
      Please don’t forgot to add internet access permission on androidmanifest.xml
      1. <uses-permission android:name="android.permission.INTERNET" />
      Now, run your application.
      Sample output
      image5 image6
      image7 image8

      Summary

      In this article, we discussed what Google Firebase is, and how to use phone number authentication on Android app with firebase authentication.