Firebase

Login with Phone Number Android

Pinterest LinkedIn Tumblr

In this post, I will tell you how to do login with phone number firebase in Android. Firebase provides almost all backend feature for developing android application. In this tutorial, we learn about firebase phone authentication using Firebase UI.

You seen many apps, they authenticate by sending SMS to user phones. User signs-in using OTP contained in this message. eg. WhatApps

Why Firebase Phone Authentication?

  • User Experience and Increased Security:- Nowadays most of people used many apps, remembering all app login credential are a headache for users. Using Firebase phone authentication increases user experience and security, as user no need to create and remember passwords. they do enter their number and do authentication by OTP.
  • Preventing Fake Users:- phone authentication is prevented fake user, means user can’t be able to register with multiple accounts.
  • Increase User Base:- All the user are verified, resultant user base will increase.

Way of implementation Firebase Phone Authentication

  1. Using Firebase UI:- This is easiest way to add phone authentication in your apps. In this methodology, firebase provides own UI for phone no sign-in.
  2. With Custom UI:- Using this approach, you create own UI and implement Phone Authentication. This approach is commonly used in todays. I have written a separate article for this

Firebase phone number authentication android example

Firebase Phone Authentication Tutorial

Let’s learn how to implement Firebase Phone Authentication using UI in Android. Let’s follow steps.

  • Create a new android studio project
  • Connect Firebase to your project
  • Configure Firebase Authentication
  • Enable Phone Number sign-in for your Firebase project
  • Start Intent for login with phone number
  • Get Result onActivityResult
1. Create a new android studio project

Open the Android Studio and create a new project. and make sure to include Google’s Maven repository in both your buildscript and allprojects sections In your project-level build.gradle.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
  repositories {
    google()
    jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.3.0'
    classpath 'com.google.gms:google-services:4.2.0'
  }
}
2. Connect Firebase to your project

In Android Studio, Go to tool menu select firebase. This will assistant menu to connect firebase with your app. On firebase, e assistant menu selects Authentication and click on Connect to Firebase.

3. Configure Firebase Authentication

Add the dependency for the Firebase Authentication in app-level build.gradle

   // phone Authentication
  implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
  implementation 'com.google.firebase:firebase-core:16.0.9'
4. Enable Phone Number sign-in for your Firebase project

To authenticate user by SMS. You must enable Phone Number sign-in method in your Firebase console. Let’s open Firebase Console, sign-in method and enable Phone Number. Now your configuration is done. Let’s move to Android Studio. For this follow snapshot

5. Open color.xml file and add this color

Add below code in color.xml in your project

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="colorPrimary">#008577</color>
  <color name="colorPrimaryDark">#00574B</color>
  <color name="colorAccent">#D81B60</color>

  <color name="media">#EA6D78</color>
  <color name="white">#FFFFFF</color>
</resources>
6. Add dimen for using xml layout

Go to res => value => create a file name is dimen.xml and below dimen values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <dimen name="margin_left_16">16dp</dimen>
  <dimen name="margin_right_16">16dp</dimen>
  <dimen name="margin_top_16">16dp</dimen>
  <dimen name="margin_bottom_16">16dp</dimen>

  <dimen name="margin_top_8">8dp</dimen>
  <dimen name="margin_bottom_8">8dp</dimen>
  <dimen name="margin_left_8">8dp</dimen>
  <dimen name="margin_right_8">8dp</dimen>

  <dimen name="margin_top_4">4dp</dimen>
  <dimen name="margin_bottom_4">4dp</dimen>
  <dimen name="margin_left_4">4dp</dimen>
  <dimen name="margin_right_4">4dp</dimen>

  <dimen name="radius_2">2dp</dimen>
  <dimen name="radius_8">8dp</dimen>
  <dimen name="radius_16">16dp</dimen>
  <dimen name="radius_24">24dp</dimen>
  <dimen name="radius_32">32dp</dimen>

  <dimen name="padding_1">1dp</dimen>
  <dimen name="padding_4">4dp</dimen>
  <dimen name="padding_8">8dp</dimen>
  <dimen name="padding_12">12dp</dimen>
  <dimen name="padding_14">14dp</dimen>
  <dimen name="padding_16">16dp</dimen>

  <dimen name="text_20">20dp</dimen>

</resources>
7. Add login button in activity_main.xml

In res => layout folder open the activity_main.xml file and add button component. We call firebase intent on this button onClick() event.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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="@drawable/teabackground"
    tools:context=".MainActivity"
    >

  <Button
      android:id="@+id/buttonPhoneAuth"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginBottom="8dp"
      android:layout_marginEnd="24dp"
      android:layout_marginStart="24dp"
      android:layout_marginTop="8dp"
      android:background="@drawable/red_style"
      android:text="Login with Phone "
      android:textAllCaps="false"
      android:textColor="@color/white"
      android:textSize="@dimen/text_20"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />

</android.support.constraint.ConstraintLayout>
8. Create background drawable for login button

Go to res folder and create a drawable resource named is red_style.xml for login button.

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"   >

    <solid
        android:color="@color/media"
        >
    </solid>

    <stroke
        android:width="1dp"
        android:color="@color/media" >
    </stroke>

    <padding
        android:left="@dimen/padding_8"
        android:top="@dimen/padding_8"
        android:right="@dimen/padding_8"
        android:bottom="@dimen/padding_8"    >
    </padding>

    <corners
        android:radius="@dimen/radius_32"   >
    </corners>

</shape>
9. Add Internet permission in AndroidManifest
<uses-permission android:name="android.permission.INTERNET"/>
10. Move to MainActivity, call firebase intent on button onClick event.

In this android app tutorial, we are using firebase UI for use phone authentication. We need to call phone authentication intent only.

package com.wave.phoneauthui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {

  Button buttonPhoneAuth;
  private static final int RC_SIGN_IN = 101;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttonPhoneAuth = findViewById(R.id.buttonPhoneAuth);
    // Set button listen
    buttonPhoneAuth.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        doPhoneLogin();
      }
    });
  }

  private void doPhoneLogin() {
    Intent intent = AuthUI.getInstance().createSignInIntentBuilder()
        .setIsSmartLockEnabled(!BuildConfig.DEBUG)
        .setAvailableProviders(Collections.singletonList(
            new AuthUI.IdpConfig.PhoneBuilder().build()))
        .setLogo(R.mipmap.ic_launcher)
        .build();

    startActivityForResult(intent, RC_SIGN_IN);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
      IdpResponse idpResponse = IdpResponse.fromResultIntent(data);

      if (resultCode == RESULT_OK) {
        // Successfully signed in
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        showAlertDialog(user);
      } else {
        /**
         *   Sign in failed. If response is null the user canceled the
         *   sign-in flow using the back button. Otherwise check
         *   response.getError().getErrorCode() and handle the error.
         */
        Toast.makeText(getBaseContext(), "Phone Auth Failed", Toast.LENGTH_LONG).show();
      }
    }
  }

  public void showAlertDialog(FirebaseUser user) {
    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(
        MainActivity.this);

    // Set Title
    mAlertDialog.setTitle("Successfully Signed In");

    // Set Message
    mAlertDialog.setMessage(" Phone Number is " + user.getPhoneNumber());

    mAlertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
        dialog.dismiss();
      }
    });
    mAlertDialog.create();

    // Showing Alert Message
    mAlertDialog.show();
  }
}

You are done

You are almost finished. That’s all for firebase authentication using phone number android. I hope it’s helpful for you, then help me by sharing this post with all your friends who learning android app development.

Requisition

Please read all Firebase articles in single place.

Download Solution Code

Still, having trouble? you can leave your comments here. Read our recent post on how to generate Android and iOS folders in React Native Thank You  🙂

2 Comments

  1. can u explain the code the video, bec there are other video and urs are complty different form others.. but urs are good..

Write A Comment