Android Studio Examples

100+ tutorials, source code, and examples to help you develop creative and technical skills.

OTP Verification using Firebase in Android Studio

gradle.build (project)

// 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:4.1.3"
        classpath 'com.google.gms:google-services:4.3.10'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

gradle.build (app)

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.0"

    defaultConfig {
        applicationId "com.learnoset.otpverification"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    testImplementation 'junit:junit:4.13.2'
    implementation platform('com.google.firebase:firebase-bom:28.4.0')
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.google.firebase:firebase-auth'
}

google-services.json

// Replace this file with your own google-services.json otherwise you may get errors in your project


{
  "project_info": {
    "project_number": "248125923302",
    "project_id": "otpverification-dd9a6",
    "storage_bucket": "otpverification-dd9a6.appspot.com"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:248125923302:android:210ed50bef84ceba74c027",
        "android_client_info": {
          "package_name": "com.learnoset.otpverification"
        }
      },
      "oauth_client": [
        {
          "client_id": "248125923302-lo8f92n4ar666i6pp8e5qg1cu5088cuo.apps.googleusercontent.com",
          "client_type": 1,
          "android_info": {
            "package_name": "com.learnoset.otpverification",
            "certificate_hash": "ce5dbf10dd6cb3a8952c3fde991ee53a45caa940"
          }
        },
        {
          "client_id": "248125923302-mkgq3pnmhma01h985qa89nuu4aijrj7g.apps.googleusercontent.com",
          "client_type": 3
        }
      ],
      "api_key": [
        {
          "current_key": "AIzaSyDD_mUfk7BHS6ED18iztolEjPx841hKZvE"
        }
      ],
      "services": {
        "appinvite_service": {
          "other_platform_oauth_client": [
            {
              "client_id": "248125923302-mkgq3pnmhma01h985qa89nuu4aijrj7g.apps.googleusercontent.com",
              "client_type": 3
            }
          ]
        }
      }
    }
  ],
  "configuration_version": "1"
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.learnoset.otpverification">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/Theme.OTPVerification">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/mobileET"
        android:inputType="phone"
        android:maxLines="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Mobile Number"/>

    <EditText
        android:visibility="gone"
        android:id="@+id/otpET"
        android:inputType="number"
        android:maxLines="1"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter OTP"/>

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/actionBtn"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Otp"/>

</LinearLayout>

MainActivity.java

package com.learnoset.otpverification;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    private boolean otpSent = false;
    private String countryCode = "+91";
    private String id = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText mobileET = findViewById(R.id.mobileET);
        final EditText otpET = findViewById(R.id.otpET);
        final Button actionBtn = findViewById(R.id.actionBtn);

        FirebaseApp.initializeApp(this);

        FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();

        actionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(otpSent){
                    final String getOTP = otpET.getText().toString();

                    if(id.isEmpty()){
                        Toast.makeText(MainActivity.this, "Unable to verify OTP", Toast.LENGTH_SHORT).show();
                    }
                    else{

                        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(id, getOTP);

                        firebaseAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {

                                if(task.isSuccessful()){

                                    FirebaseUser userDetails = task.getResult().getUser();

                                    Toast.makeText(MainActivity.this, "Verified", Toast.LENGTH_SHORT).show();
                                }
                                else{
                                    Toast.makeText(MainActivity.this, "Something went wrong!!!", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                }
                else{
                    final String getMobile = mobileET.getText().toString();

                    PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
                            .setPhoneNumber(countryCode+""+getMobile)
                            .setTimeout(60L, TimeUnit.SECONDS)
                            .setActivity(MainActivity.this)
                            .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                                @Override
                                public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
                                    Toast.makeText(MainActivity.this, "OTP sent successfully", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onVerificationFailed(@NonNull FirebaseException e) {

                                    Toast.makeText(MainActivity.this, "Something went wrong "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                                    super.onCodeSent(s, forceResendingToken);
                                    otpET.setVisibility(View.VISIBLE);
                                    actionBtn.setText("Verify OTP");
                                    id = s;
                                    otpSent = true;
                                }
                            }).build();

                    PhoneAuthProvider.verifyPhoneNumber(options);
                }

            }
        });
    }
}

Projects with Source Code + Video Tutorials

You can download our Java and Android Studio Projects with Source Code and Video Tutorials.

Login-&-Register-Screen-UI-Design---02
Login & Register Screen UI Design - 02
Create-your-own-Web-Browser-Source-Code
Create your own Web Browser Source Code
Firebase-Push-Notifications-|-Background-Notification
Firebase Push Notifications | Background Notification

If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com

Follow us to learn Coding and get in touch with new Technologies.