In the last post, I showed you how to upload Image to Firebase and show the uploaded Image in ImageView. Today, I will show you how to add Phone Number Authentication in Android app using Firebase. We have used FirebaseUI library for achieving authentication.

Prerequisites

Make sure that your app is connected to Firebase.

FirebaseUI

As mentioned earlier, we will be using FirebaseUI Android library for this. The main advantage of using FirebaseUI is that it is secure and hence you don’t have to write complex code of encrypting the user credentials. And it also handles all the cases, right from maintaining user sessions to password recovery.

 

The below flowchart shows all the cases handled by FirebaseUI.

Firebase Authentication FlowchartGetting Started

Add the following dependency to your app level build.gradle file to use FirebaseUI.

compile 'com.firebaseui:firebase-ui:2.0.1'

Make sure to add the Fabric repository to your project level build.gradle file. To do so, add the highlighted line.

allprojects {
    repositories {
        // ...
        maven { url 'https://maven.fabric.io/public' }
    }
}

 

Phone Number Authentication

Go to Firebase Console, select your project and click on Authentication tab. Click on Sign-in method, select Phone and enable itOnce you enable the option, a prompt will be shown asking for further configurations. You can ignore the message and click on save.

Phone Number Authentication Firebase Android

Now we need to add SHA Certificate Fingerprint for Google Login to work. For generating SHA, go to Android Studio, click on Gradle -> :app -> android and then double click on signingReport.

SHA in Android Studio

On opening Gradle console, you can see the SHA.

SHA in Android Studio

Now open Firebase, click on the Settings icon, scroll down and click on Add Fingerprint and copy the generated SHA.

Add SHA in Firebase

Create an activity named PhoneNumberAuthentication and add the below code. Also, don’t forget to add this activity in your manifest file.

PhoneNumberAuthentication.java

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.ErrorCodes;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.ResultCodes;
import com.google.firebase.auth.FirebaseAuth;
import java.util.Arrays;


public class PhoneNumberAuthentication extends AppCompatActivity {

    private static final int RC_SIGN_IN = 123;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FirebaseAuth auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null) {

            // already signed in
            startActivity(new Intent(PhoneNumberAuthentication.this, MainActivity.class));
            finish();

        } else {

            // not signed in
            startActivityForResult(
                    AuthUI.getInstance()
                            .createSignInIntentBuilder()
                            .setAvailableProviders(
                                    Arrays.asList(
                                            new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build()
                                            ))
                            .build(),
                    RC_SIGN_IN);

        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow.
        if (requestCode == RC_SIGN_IN) {
            IdpResponse response = IdpResponse.fromResultIntent(data);

            // Successfully signed in
            if (resultCode == ResultCodes.OK) {
                startActivity(new Intent(PhoneNumberAuthentication.this,MainActivity.class));
                finish();
                return;
            } else {
                // Sign in failed
                if (response == null) {
                    // User pressed back button
                    Log.e("Login","Login canceled by User");
                    return;
                }

                if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
                    Log.e("Login","No Internet Connection");
                    return;
                }

                if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
                    Log.e("Login","Unknown Error");
                    return;
                }
            }

            Log.e("Login","Unknown sign in response");
        }
    }
}

Now when you run the app, you can see the Phone Number Authentication in action. If you face any problems, write it in the comment section and I will help you with that.

UI Customization

In order to customize the UI, make sure you have defined your app name in strings.xml file by a resource named app_name as shown below.

<resources>
    <string name="app_name">My Awesome App</string>
</resources>

Now create your own custom style in the styles.xml file and edit the UI as per your need. The custom style you create should have FirebaseUI as the parent and the three standard AppCompat color must be defined. For the demo, I am creating a style having the purple theme as shown below.

<style name="PurpleTheme" parent="FirebaseUI">
    <!-- Required standard AppCompat colors -->
    <item name="colorPrimary">@color/material_purple_500</item>
    <item name="colorPrimaryDark">@color/material_purple_700</item>
    <item name="colorAccent">@color/material_yellow_a700</item>
    
    <item name="colorControlNormal">@color/material_purple_500</item>
    <item name="colorControlActivated">@color/material_majenta_a700</item>
    <item name="colorControlHighlight">@color/material_purple_a200</item>
    <item name="android:windowBackground">@color/material_purple_50</item>
</style>

Once the custom style is created, set it in the sign-in intent as shown below.

startActivityForResult(
    AuthUI.getInstance(this).createSignInIntentBuilder()
        // ...
        .setTheme(R.style.PurpleTheme)
        .build());

If you also want to change the text that appears during the login flow, here’s the list.

<resources>
    <string name="fui_progress_dialog_loading" translation_description="Loading text in dialog">Loading…</string>
    <string name="fui_sign_in_default" translation_description="Button text to sign in">Sign in</string>
    <string name="fui_general_error" translation_description="Toast text flashing general error">An error has occurred.</string>
    <string name="fui_idp_name_google">Google</string>
    <string name="fui_idp_name_facebook">Facebook</string>
    <string name="fui_idp_name_twitter">Twitter</string>
    <string name="fui_provider_name_email">Email</string>
    <string name="fui_provider_name_phone">Phone</string>
    <string name="fui_sign_in_with_google" translation_description="Sign in button text">Sign in with Google</string>
    <string name="fui_sign_in_with_facebook" translation_description="Sign in button text">Sign in with Facebook</string>
    <string name="fui_sign_in_with_twitter" translation_description="Sign in button text">Sign in with Twitter</string>
    <string name="fui_sign_in_with_email" translation_description="Sign in button text">Sign in with email</string>
    <string name="fui_sign_in_with_phone" translation_description="Sign in button text">Sign in with phone</string>
    <string name="fui_next_default" translation_description="Button text to continue">Next</string>
    <string name="fui_email_hint" translation_description="Hint in email input field">Email</string>
    <string name="fui_phone_hint" translation_description="Hint for phone input field">Phone number</string>
    <string name="fui_password_hint" translation_description="Hint for password input field">Password</string>
    <string name="fui_required_field" translation_description="Inline error for required field">You can\'t leave this empty.</string>
    <string name="fui_invalid_email_address" translation_description="Inline error for invalid email address">Incorrect email address</string>
    <string name="fui_missing_email_address" translation_description="Inline error for empty email address in input field">Enter your email address to continue</string>
    <string name="fui_progress_dialog_checking_accounts" translation_description="Progress dialog text while checking for existing accounts">Checking for existing accounts…</string>
    <string name="fui_title_register_email" translation_description="Title for signup form">Sign up</string>
    <string name="fui_name_hint" translation_description="Hint for last name input field">First name &amp; surname</string>
    <string name="fui_button_text_save" translation_description="Button text to save input form">Save</string>
    <string name="fui_progress_dialog_signing_up" translation_description="Dialog text while waiting for server's signup response">Signing up…</string>
    <plurals name="fui_error_weak_password" translation_description="Inline error for weak password"> <item quantity="one">Password not strong enough. Use at least %1$d character and a mix of letters and numbers</item> <item quantity="other">Password not strong enough. Use at least %1$d characters and a mix of letters and numbers</item> </plurals>
    <string name="fui_email_account_creation_error" translation_description="Inline error for signup failure">Email account registration unsuccessful</string>
    <string name="fui_error_user_collision" translation_description="Inline error when user signs up using an existing email account">An account already exists with that email address.</string>
    <string name="fui_create_account_preamble_tos_and_pp" translation_description="Text shown when creating an account with both terms of service and privacy policy.">By tapping %1$s you are indicating that you agree to the %2$s and the %3$s.</string>
    <string name="fui_create_account_preamble_tos_only" translation_description="Text shown when creating an account with only terms of service">By tapping %1$s you are indicating that you agree to the %2$s.</string>
    <string name="fui_create_account_preamble_pp_only" translation_description="Text shown when creating an account with only privacy policy">By tapping %1$s you are indicating that you agree to the %2$s.</string>
    <string name="fui_terms_of_service" translation_description="Link text to web url containing the app's terms of service">Terms of Service</string>
    <string name="fui_privacy_policy" translation_description="Link text to web url containing the app's privacy policy">Privacy Policy</string>
    <string name="fui_welcome_back_idp_header" translation_description="Inline subtitle to users whose signup was interrupted since an existing account was detected">You already have an account</string>
    <string name="fui_welcome_back_email_header" translation_description="Message for returning users">Welcome back!</string>
    <string name="fui_welcome_back_idp_prompt" translation_description="Message to users that need to signin using existing IDP accounts">You\'ve already used %1$s. Sign in with %2$s to continue.</string>
    <string name="fui_welcome_back_password_prompt_body" translation_description="Message to users that need to signin using existing email accounts">You\'ve already used %1$s to sign in. Enter your password for that account.</string>
    <string name="fui_progress_dialog_signing_in" translation_description="Progress dialog text">Signing in…</string>
    <string name="fui_trouble_signing_in" translation_description="Link leading to forgot password flow">Trouble signing in?</string>
    <string name="fui_title_recover_password_activity" translation_description="Recover password screen title">Recover password</string>
    <string name="fui_title_confirm_recover_password" translation_description="Password recovery confirmation message">Check your email</string>
    <string name="fui_password_recovery_body" translation_description="Password recovery message body">Receive instructions to this email that explain how to reset your password.</string>
    <string name="fui_button_text_send" translation_description="Button text to send recovery email">Send</string>
    <string name="fui_confirm_recovery_body" translation_description="Alert dialog displayed after password recovery email is sent">Follow the instructions sent to %1$s to recover your password.</string>
    <string name="fui_progress_dialog_sending" translation_description="Progress dialog while password recovery email is being sent">Sending…</string>
    <string name="fui_error_email_does_not_exist" translation_description="Inline error when user attempt signin with invalid account">That email address doesn\'t match an existing account</string>
    <string name="fui_accessibility_logo" translation_description="Content description for app logo">App logo</string>
    <string name="fui_signed_in_with_specific_account" translation_description="Post signin message showing method of authentication">Signed in as %1$s</string>
    <string name="fui_verify_phone_number_title" translation_description="Phone number entry form title">Enter your phone number</string>
    <string name="fui_invalid_phone_number" translation_description="Inline error when phone number entered is invalid">Enter a valid phone number</string>
    <string name="fui_enter_confirmation_code" translation_description="Phone number verification code entry form title">Enter the 6-digit code that we sent to</string>
    <string name="fui_resend_code_in" translation_description="Countdown timer text that the user needs to wait for before attempting to resend verification sms">Resend code in 0:%02d</string>
    <string name="fui_verify_your_phone_title" translation_description="Button text to complete phone number verification">Verify your phone number</string>
    <string name="fui_verifying" translation_description="Progress dialog text while phone number is being verified">Verifying…</string>
    <string name="fui_retrieving_sms" translation_description="Progress dialog text when sms is being retrieved before auto-submit">Retrieving SMS…</string>
    <string name="fui_incorrect_code_dialog_body" translation_description="Inline error when incorrect sms verification code is being used to verify">Wrong code. Try again.</string>
    <string name="fui_incorrect_code_dialog_positive_button_text" translation_description="Text to dismiss error alert dialog">OK</string>
    <string name="fui_error_too_many_attempts" translation_description="Error message when the phone number has been used too many times">This phone number has been used too many times</string>
    <string name="fui_error_quota_exceeded" translation_description="Error message when the Firebase project's quota has been exceeded.">There was a problem verifying your phone number</string>
    <string name="fui_error_session_expired" translation_description="Error message when SMS confirmation code has expired.">This code is no longer valid</string>
    <string name="fui_sign_in_with_phone_number" translation_description="Label for phone number input form">Sign in with phone number</string>
    <string name="fui_done" translation_description="Progress dialog success transition once sms is sent">Done</string>
    <string name="fui_verified" translation_description="Progress dialog success transition when phone number was verified">Verified.</string>
    <string name="fui_code_sent" translation_description="Progress dialog success transition once sms is sent">Code sent.</string>
    <string name="fui_resending" translation_description="Progress dialog text when user clicks on resend sms">Resending…</string>
    <string name="fui_resend_code" translation_description="Link text to resend verification sms">Resend code</string>
    <string name="fui_verify_phone_number" translation_description="Button text to submit confirmation code and complete phone verification">Verify Phone Number</string>
    <string name="fui_continue_phone_login" translation_description="Button text to submit phone number and send sms">Continue</string>
    <string name="fui_sms_terms_of_service" translation_description="Fine print warning displayed below Verify Phone Number button">By tapping %1$s, an SMS may be sent. Message &amp; data rates may apply.</string>
</resources>

 

Categories: AndroidTutorials

  • Mahaveer

    Hi, can you please share the full source code ?

    • The Engineer’s Cafe

      Here’s the link to the project.

      https://goo.gl/pH37Jw

      • Mahaveer

        Thanks Sir.Looking forward for more tutorials from you.

        • The Engineer’s Cafe

          Welcome 🙂

  • Pingback: Upload an Image to Firebase Storage (Firebase Tutorial #4) - The Engineer's Cafe()

  • Abhinav Maurya

    please send whole project file! getting this error!

    Error:Execution failed for task ‘:app:processDebugManifest’.
    > Manifest merger failed : Attribute meta-data#io.fabric.ApiKey@value value=(3673f38136ae2e2cc121c6dedb8804fc6929af2c) from AndroidManifest.xml:98:13-69
    is also present at [com.firebaseui:firebase-ui-auth:2.0.1] AndroidManifest.xml:21:13-60 value=(@string/twitter_consumer_secret).
    Suggestion: add ‘tools:replace=”android:value”‘ to element at AndroidManifest.xml:96:9-99:15 to override.

    • The Engineer’s Cafe

      You forgot to add fabric maven url to your project. Edit your project level build.gradle files as shown below.

      allprojects {
      repositories {
      // …
      maven { url ‘https://maven.fabric.io/public’ }
      }
      }

      I have also written this in the above article in getting started. Check it if you need.

      • Abhinav Maurya

        still not working

        • The Engineer’s Cafe

          Are you getting the same error?

    • Edit your project level build.gradle files as shown below.

      allprojects {
      repositories {
      // …
      maven { url ‘https://maven.fabric.io/pub… }
      }
      }

  • Nikhil Patil

    an internal error has occurred INVALID_APP-CREDENTIAL:App validation failed

    app run …bt when i insert mobile number and click on register it gives above msg

    • The Engineer’s Cafe

      It looks like you forgot to add SHA credentials to Firebase. Add it and everything will work fine.

      • Nikhil Patil

        it is already added…code work fine…
        bt now i integrate with my project,,so it gives problem now..

        • The Engineer’s Cafe

          Make sure to update google play services and Firebase dependencies. If they are not upto date, it causes runtime exception.

      • Nikhil Patil
        • The Engineer’s Cafe

          Try this:
          1) Make sure you have atleast one Google account already logged in.
          2) Don’t try on emulator. Run on a real Android device.
          3) Update google play service and firebase dependencies. They should be latest in order for the code to work.

  • PJ

    i followed the same steps.. but after i debug app its not working…help required

    • The Engineer’s Cafe

      Can you please tell me the error?

  • thailandy asmr

    HI , you are best really , can you share apk demo for test it please ?

    thanks again

    • The Engineer’s Cafe

      Hey, thanks for the kind words.

      Actually I wrote this code on my PC which became dead few days ago. So I have lost access to the source code 🙁

      Sorry for inconvenience.

  • Vivek Shukla

    Error:Execution failed for task ‘:app:processDebugManifest’.
    > Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library [com.firebaseui:firebase-ui:2.0.1] C:UsersAdminAndroidStudioProjectsPhoneNumberTestappbuildintermediatesexploded-aarcom.firebaseuifirebase-ui2.0.1AndroidManifest.xml
    Suggestion: use tools:overrideLibrary=”com.firebase.ui” to force usage

    This is the error which I’m getting please help me in solving this problem

  • Golu Boi

    Do we have to make the phone number authentication activity as the launcher activity?

    • If you want to show some other screens before login then don’t and if you want to directly authenticate user then make it as a launcher activity.

      • Golu Boi

        Thanks 🙂

  • Golu Boi

    How to change the time of resending OTP?

  • Golu Boi

    Can we modify the way the login screen appears? Like the color or the size of buttons or something like that?
    Also, could you give me the link of the sites from where you learnt Phone Authentication using FirebaseUI as I want to make some customisations to the login.

    And I must tell you, yours is the only tutorial that I found on the Internet about Phone Authentication using FirebaseUI. Other tutorials only show the conventional, non FirebaseUI method, which is more complex. Great work!

  • Amrata Baghel

    I have done the same code but when I click on verify my phone number after entering my phone number, I get the error MISSING_CLIENT_IDENTIFIER. Can you help me with this?

  • swasthik shetty

    im gettting this error
    IllegalArgumentException: error getting error html: unexpected add suggestion format add ‘tools:replace=”android:value”‘ to element at AndroidManifest.xml:56:9-58:46 to override.

Related Posts

Android

Add Admob Native Ads in Android (RecyclerView)

Admob Native Ads is an ad format that gives developers the freedom to customize the look of their ad and match it with the overall design of the app. Today in this tutorial, I will show you how to add Native ads in RecyclerView. 

Android

Add Shimmer Effect to Android app

Rather than the same old circular loader, you can add shimmer effect to Android app when it is loading. This tutorial shows how you can add shimmer effect to your Android app.

Android

Upload an Image to Firebase Storage (Firebase Tutorial #4)

Today, I am going to show you how to upload an image to Firebase storage and then show that uploaded image in an ImageView in Android.

Subscribe and get a free eBook on 8 Tips to level up your Android Development Skills.

(We hate spam as much as you do)

You have Successfully Subscribed!

%d bloggers like this: