Intermediate 35 min Java Full project

Phone Number Login with Firebase in Android Studio

Let people sign in with their phone number: Firebase sends an SMS code and your app verifies it. Passwordless and familiar to users.

What you'll learn

  • Turn on Phone sign-in in Firebase
  • Send a verification code by SMS
  • Verify the code and sign the user in
  • Open a home screen after login

Before you start

  • Android Studio (any recent version)
  • Basic Java: variables, methods and if/else
  • A free Firebase project (console.firebase.google.com)
  • A real Android phone with a SIM

How it fits together

  1. 1Enter +country number
  2. 2verifyPhoneNumber
  3. 3SMS code
  4. 4signInWithCredential
  5. 5HomeActivity

Build it step by step

1. Create a Firebase project

In the Firebase console, add an Android app with your package name (com.example.phoneauth to copy the code unchanged) and download google-services.json into the app folder.

2. Add your app's fingerprints

Phone sign-in checks that requests come from your real app. In Android Studio's terminal run ./gradlew signingReport, then copy the SHA-1 and SHA-256 into the Firebase app settings.

3. Turn on phone sign-in

In Authentication → Sign-in method, enable Phone. To test without real SMS, add a test number and code there (for example +1 650-555-1234 with code 123456).

4. Add Firebase to the app

In app/build.gradle.kts, add the plugin and dependencies:

kotlin
plugins {
    id("com.google.gms.google-services")
}

dependencies {
    implementation(platform("com.google.firebase:firebase-bom:35.1.0"))
    implementation("com.google.firebase:firebase-auth")
}

In the project-level build.gradle.kts, add:

kotlin
plugins {
    id("com.google.gms.google-services") version "4.5.0" apply false
}

Then press Sync Now.

5. Send the code

Ask for the number with the country code (+91...). PhoneAuthProvider.verifyPhoneNumber sends the SMS. Its callbacks tell you what happened:

  • onCodeSent: save the verification ID and show the code box.
  • onVerificationCompleted: Android read the SMS for you; sign in straight away.
  • onVerificationFailed: show a message.

6. Check the code

Combine the verification ID with the typed code using PhoneAuthProvider.getCredential, then call signInWithCredential.

7. Resend

Keep the ForceResendingToken from onCodeSent and pass it when the user taps Send again.

8. Remember the user

On launch, if getCurrentUser() isn't null, go straight to Home. Log out calls signOut().

9. Run it

Run on a real phone with a SIM, or use your test number.

If something goes wrong

  • "This app is not authorized": add the SHA-1 and SHA-256 fingerprints, then download google-services.json again.
  • No SMS arrives: check the number includes + and the country code, and that Phone sign-in is enabled.
  • Testing on an emulator: use a test phone number from step 3.

What's improved over the video

Both steps sit on one clear screen, it handles automatic SMS reading and resending, errors appear under the right field, and returning users skip straight to Home.

Required setup

These are additions to an existing project—not replacement project files.

Add Firebase Authentication

Add these lines

Where: app/build.gradle.kts and build.gradle.kts

Add the plugin and dependencies, put google-services.json in the app folder, then Sync Now.

app/build.gradle.kts and build.gradle.kts
// app/build.gradle.kts
plugins {
    id("com.google.gms.google-services")
}

dependencies {
    implementation(platform("com.google.firebase:firebase-bom:35.1.0"))
    implementation("com.google.firebase:firebase-auth")
}

// project-level build.gradle.kts
plugins {
    id("com.google.gms.google-services") version "4.5.0" apply false
}

Application code

Select a file to see its code and where it belongs.

This code uses package com.example.phoneauth. Change that first line to your own package, the one at the top of your MainActivity.

Replace fileapp/src/main/java/com/example/phoneauth/MainActivity.java

Sends the SMS code, verifies it, and signs in. Skips straight to Home if already signed in.

MainActivity.java
package com.example.phoneauth;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

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

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;

/**
 * Step 1: enter a phone number and send a code. Step 2: enter the 6-digit code.
 * Firebase sends the SMS and checks the code; often it reads the SMS automatically.
 */
public class MainActivity extends AppCompatActivity {
    private final FirebaseAuth auth = FirebaseAuth.getInstance();
    private String verificationId;
    private PhoneAuthProvider.ForceResendingToken resendToken;

    TextInputLayout phoneLayout, codeLayout;
    TextInputEditText phone, code;
    Button sendButton, verifyButton;
    TextView resend, stepTitle;
    ProgressBar progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Already signed in? Go straight to Home.
        if (auth.getCurrentUser() != null) {
            openHome();
            return;
        }
        Screens.setUp(this, R.layout.activity_main);

        phoneLayout = findViewById(R.id.phoneLayout);
        codeLayout = findViewById(R.id.codeLayout);
        phone = findViewById(R.id.phone);
        code = findViewById(R.id.code);
        sendButton = findViewById(R.id.buttonSend);
        verifyButton = findViewById(R.id.buttonVerify);
        resend = findViewById(R.id.textResend);
        stepTitle = findViewById(R.id.textStep);
        progress = findViewById(R.id.progress);

        sendButton.setOnClickListener(v -> sendCode(null));
        resend.setOnClickListener(v -> sendCode(resendToken));
        verifyButton.setOnClickListener(v -> {
            String typed = String.valueOf(code.getText()).trim();
            if (typed.length() != 6 || verificationId == null) {
                codeLayout.setError(getString(R.string.error_code));
                return;
            }
            signIn(PhoneAuthProvider.getCredential(verificationId, typed));
        });
    }

    private void sendCode(PhoneAuthProvider.ForceResendingToken token) {
        String number = String.valueOf(phone.getText()).replace(" ", "");
        // Firebase needs the full international number, starting with + and the country code.
        if (!number.matches("\\+\\d{8,15}")) {
            phoneLayout.setError(getString(R.string.error_phone));
            return;
        }
        phoneLayout.setError(null);
        setBusy(true);
        PhoneAuthOptions.Builder options = PhoneAuthOptions.newBuilder(auth)
                .setPhoneNumber(number)
                .setTimeout(60L, TimeUnit.SECONDS)
                .setActivity(this)
                .setCallbacks(callbacks);
        if (token != null) options.setForceResendingToken(token);
        PhoneAuthProvider.verifyPhoneNumber(options.build());
    }

    private final PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks =
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
                    // Android read the SMS for us (or the number was verified instantly).
                    signIn(credential);
                }

                @Override
                public void onVerificationFailed(@NonNull FirebaseException e) {
                    setBusy(false);
                    phoneLayout.setError(getString(R.string.error_send));
                }

                @Override
                public void onCodeSent(@NonNull String id, @NonNull PhoneAuthProvider.ForceResendingToken token) {
                    setBusy(false);
                    verificationId = id;
                    resendToken = token;
                    showCodeStep();
                }
            };

    private void signIn(PhoneAuthCredential credential) {
        setBusy(true);
        auth.signInWithCredential(credential).addOnCompleteListener(this, task -> {
            setBusy(false);
            if (task.isSuccessful()) openHome();
            else codeLayout.setError(getString(R.string.error_code));
        });
    }

    private void showCodeStep() {
        stepTitle.setText(R.string.step_code);
        phoneLayout.setEnabled(false);
        sendButton.setVisibility(View.GONE);
        codeLayout.setVisibility(View.VISIBLE);
        verifyButton.setVisibility(View.VISIBLE);
        resend.setVisibility(View.VISIBLE);
        code.requestFocus();
    }

    private void setBusy(boolean busy) {
        progress.setVisibility(busy ? View.VISIBLE : View.GONE);
        sendButton.setEnabled(!busy);
        verifyButton.setEnabled(!busy);
    }

    private void openHome() {
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }
}

Full source code