• Facebook
  • Twitter
  • YouTube
  • LinkedIn
AndroidWave
  • Home
  • Tech
    1. React Native
    2. Core Android
    3. Architecture Components
    4. Coroutines
    5. View All
    Cardview in react native example
    February 24, 2021
    Best React Native Development Tools
    April 18, 2019
    How to Install and Setup React Native on Ubuntu
    April 17, 2019
    Android SharedPreferences Example | Kotlin
    December 9, 2020
    Android check internet connection
    December 9, 2020
    Double Tap Listener Android Example
    June 9, 2020
    Android Capture Signature using Canvas and Save
    December 22, 2019
    Android TextView enable Copy Paste
    December 10, 2019
    Best Practices of Runtime Permissions Android
    November 26, 2019
    Download and Install APK Programmatically
    November 25, 2019
    Android force update using Firebase
    October 3, 2019
    Navigation Architecture Component in Android
    January 13, 2020
    Manifest merger failed with multiple errors
    July 27, 2019
    Android Data Binding RecyclerView
    June 15, 2019
    Android Paging Library
    May 22, 2019
    Scheduling Recurring Task in Android | WorkManager
    April 14, 2019
    WorkManager Constraints | Running Tasks Under Specific Conditions
    April 8, 2019
    Android WorkManager Tutorial
    March 26, 2019
    Loading Images Using Data Binding – Glide
    March 25, 2019
    Coroutines background processing
    April 27, 2021
    Exception handling in coroutines
    March 3, 2021
    Coroutines withContext example
    February 28, 2021
    Coroutine async and await example
    February 26, 2021
    Android retrofit with coroutines Kotlin
    February 23, 2021
    Dispatchers in Kotlin Coroutines
    February 19, 2021
    Kotlin Coroutines Job Example
    February 18, 2021
    Suspending functions in Coroutine
    February 18, 2021
    Android SharedPreferences Example | Kotlin
    December 9, 2020
    Android check internet connection
    December 9, 2020
    Double Tap Listener Android Example
    June 9, 2020
    Android Capture Signature using Canvas and Save
    December 22, 2019
    Android TextView enable Copy Paste
    December 10, 2019
    Best Practices of Runtime Permissions Android
    November 26, 2019
    Download and Install APK Programmatically
    November 25, 2019
    Android force update using Firebase
    October 3, 2019
    Previous Next
  • About
  • Contact
  • Search for:
Home ยป Login with Phone Number Android
Firebase

Login with Phone Number Android

By Surya May 26, 2019
login with phone number firebase android

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

Download Zip

Still, having trouble? you can leave your comments here. Thank You  ๐Ÿ™‚

Related Posts

Firebase in-app messaging android

April 4, 2021

Send FCM message from Android

February 2, 2020

Firebase Cloud Messaging Android

January 23, 2020

2 Comments

  1. prasant 3 years ago Reply

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

  2. zain 3 years ago Reply

    BrCan You Make A Video On It

Write A Comment Cancel Reply

  • Join our weekly newsletter

    Enter your email address below to subscribe to my newsletter

  • POPULAR
    • ExoPlayer in RecyclerView in Android

      September 21, 2018
    • Play Youtube Video in ExoPlayer

      December 18, 2018
    • Automatic SMS Verification Android

      May 22, 2019
    • Foreground Service Android Example

      May 1, 2019
  • CATEGORIES
    • Android Architecture (5)
    • Architecture Components (17)
    • Core Android (41)
    • Coroutines (10)
    • DI & UnitTest (1)
    • Firebase (8)
    • Kotlin (6)
    • Libraries (12)
    • React Native (3)
    • UI/UX (16)

AndroidWave - Android Developer Blog | Our Privacy Policy

Top
  • Home
  • Tech
    • React Native
    • Core Android
    • Architecture Components
    • Coroutines
  • About
  • Contact

Type above and press Enter to search. Press Esc to cancel.

Go to mobile version