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.

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?

  • 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.

Related Posts

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.

Android

Save and Retrieve data from Firebase in Android (Firebase Tutorial #3)

This tutorial shows a step by step guide on how to save and retrieve data in Firebase Realtime Database using an Android app.

%d bloggers like this: