In this article, I am going to explain how to use phone number authentication on Android with Google firebase, which allows users to sign in using their phone number by receiving a One Time Password SMS.
Firebase
Firebase is a backend tool for mobile and web applications.
It offers Analytics, Cloud Messaging, Real-time Database, Storage, Remote Configuration, Notification, Crash Reporting, API’s, Multiple Authentication types, Hosting, Dynamic Links and Invites.
Google Firebase helps to develop the Application rapidly.
Requirements
- Android Studio.
- Google Account.
Follow the steps given below to build an Android application
Open an Android Studio and create a new project.
Login to Google Firebase and create a new project in console.
After creating the project select “Add Firebase to your Android app” in Firebase overview page.
After adding an Application, give your Android application package name, App nickname and Debug signing certificate SHA-1 hit REGISTERAPP.
Now, download Google-services.json file add into your application; app folder.
Adding Dependencies
Add the dependencies plug-in in App gradle for firebase phone authentication.
- compile 'com.google.firebase:firebase-auth:11.0.4'
Add Gradle plug-in (build.gradle(app)) end of the code.
- apply plugin: 'com.google.gms.google-services'
Add classpath plug-in in project gradle
- classpath 'com.google.gms:google-services:3.1.0'
Enable Phone Number sign-in for your Firebase project
In the Firebase console, open the Authentication section.
On the Sign-in Method page, enable the Phone Number sign-in method.
Now, go to Android Studio and copy the code.
Creating Layout
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/activity_main"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context="io.github.saravanan_selvaraju.phoneauthentication.MainActivity">
- <EditText
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="Phone Number"
- android:inputType="phone"
- android:padding="15dp"
- android:maxLength="10"
- android:id="@+id/phone"/>
- <EditText
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:padding="15dp"
- android:id="@+id/code"
- android:hint="Verification Code"
- android:visibility="gone"/>
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Verify"
- android:layout_below="@+id/phone"
- android:id="@+id/getcode"
- android:padding="15dp"
- android:onClick="GetCode"/>
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/verify"
- android:layout_below="@+id/code"
- android:text="Verify"
- android:onClick="verify"
- android:padding="15dp"
- android:visibility="gone"/>
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:id="@+id/msgtxt"
- android:layout_centerInParent="true"
- android:text="Signin Successfully"
- android:padding="5dp"
- android:textColor="#000000"
- android:visibility="gone"/>
- </RelativeLayout>
Creating Activity
- package io.github.saravanan_selvaraju.phoneauthentication;
-
- import android.content.Intent;
- import android.support.annotation.NonNull;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
-
- import com.google.android.gms.tasks.OnCompleteListener;
- import com.google.android.gms.tasks.Task;
- import com.google.firebase.FirebaseException;
- import com.google.firebase.FirebaseTooManyRequestsException;
- import com.google.firebase.auth.*;
- import java.util.concurrent.TimeUnit;
-
- public class MainActivity extends AppCompatActivity {
- EditText phone,vcode;
- TextView msg;
- Button getcode,verify;
- private FirebaseAuth mAuth;
- private String mVerificationId;
- private PhoneAuthProvider.ForceResendingToken mResendToken;
- private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- phone = (EditText) findViewById(R.id.phone);
- vcode = (EditText) findViewById(R.id.code);
- getcode=(Button)findViewById(R.id.getcode);
- verify=(Button)findViewById(R.id.verify);
- msg=(TextView)findViewById(R.id.msgtxt);
- mAuth = FirebaseAuth.getInstance();
- mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
-
- @Override
- public void onVerificationCompleted(PhoneAuthCredential credential) {
- Toast.makeText(MainActivity.this,"Verified",Toast.LENGTH_LONG).show();
- vcode.setVisibility(View.GONE);
- verify.setVisibility(View.GONE);
- msg.setVisibility(View.VISIBLE);
- }
-
- @Override
- public void onVerificationFailed(FirebaseException e) {
- Toast.makeText(MainActivity.this,"Login Faled",Toast.LENGTH_LONG).show();
-
- if (e instanceof FirebaseAuthInvalidCredentialsException) {
-
-
- } else if (e instanceof FirebaseTooManyRequestsException) {
-
- }
-
- }
-
- @Override
- public void onCodeSent(String verificationId,
- PhoneAuthProvider.ForceResendingToken token) {
-
- mVerificationId = verificationId;
- mResendToken = token;
-
- }
- };
-
-
- }
-
- public void GetCode(View view) {
- PhoneAuthProvider.getInstance().verifyPhoneNumber(
- phone.getText().toString(),
- 60,
- TimeUnit.SECONDS,
- this,
- mCallbacks);
- phone.setVisibility(View.GONE);
- getcode.setVisibility(View.GONE);
- vcode.setVisibility(View.VISIBLE);
- verify.setVisibility(View.VISIBLE);
-
- }
-
- public void verfy(View view) {
-
- PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, vcode.getText().toString());
- signInWithPhoneAuthCredential(credential);
- }
- private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- if (task.isSuccessful()) {
- vcode.setVisibility(View.GONE);
- verify.setVisibility(View.GONE);
- msg.setVisibility(View.VISIBLE);
- } else {
- if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
- Toast.makeText(MainActivity.this,"Invslid code",Toast.LENGTH_LONG).show();
- }
- }
- }
- });
- }
- }
Please don’t forgot to add internet access permission on androidmanifest.xml
- <uses-permission android:name="android.permission.INTERNET" />
Now, run your application.
Sample output
Summary
In this article, we discussed about what Google Firebase is, and how to use phone number authentication on Android app with firebase authentication.