Login with Google Using Firebase Authentication in Android Studio (Tutorial)

Do you want to make your users fall in love with your app by creating a smooth UX through login Google account using Firebase? If yes, go ahead to read on.

I don’t need to emphasize what modern users have become — they want the fastest mobile, fastest internet, and fastest pizza delivery.

You might be thinking what’s wrong on asking the critical pieces of information like email, first and last name, and password.

The problem is that users are addicted to the apps that allow instant sign in with Google.

Furthermore, you must understand one fundamental rule in your life to be good at anything. You have to follow the best competitors in the world.

What does it mean?

It means you’ll need to follow the same standards, frameworks, and techniques that the best competitors implement in their apps since they’ve hired the best CRO, ASO and copywriter experts.

TL;DR of the feature is that it:

  • Saves time for both the developers and the end-users.
  • Gets all the information that you need like: name & emails

Quick Jumps

How Does It Work? (Video)

 

More than a billion users are already signed in with Google Play with their Google accounts. When an app authenticates and gets all the information from Google Play.

If a user isn’t signed in with Google Play, it’s essential to sign in to enjoy the app that is an unlikely cause.

Login with Google Using Firebase in Android Studio (Step by Step)

Create a new project in Android Studio

Create a New Project in Android Studio. How? You need to click on File -> New -> New Projects.

Create New Project

 

Click on Empty Activity -> Next

Empty Activity

 

Enter Name -> and Click Next

Name

Adding Firebase to Android Project

Add Firebase to your project.

by clicking on Tools -> Firebase

opening Firebase Assistant

Now Firebase Assistant is open on the right side as you can see in the image below, then click on Email and Password Authentication.

Authentication

Now click Connect to Firebase

Connect To Firebase

Now if you are not signed with Android Studio then a window appears in the browser where you’ll need sign in to Google account.

Login console

Then click Next.

Login Console Next

Now you are logged in on Android Studio and an email is also sent through google to your computer stating that “You’ve signed in with Android Studio“.

Login console success

Now open Android Studio you can see a popup box appear just like below. Enter ProjectName (if you want to change) then Select Country and click Connect to Firebase.

New Firebase Project

You’re good to go if you see a green color text ✔️ Connected on the bottom right side of the screen. Now click on Add Firebase Authentication to your app.

add Firebase Authentication To app

A popup box appears now click Accept Changes. This will add some dependencies to your project at the app-level and the Project-level.

Accept Changes

Now you can see dependencies set up correctly.

Dependencies setup correctly

Now open https://console.firebase.google.com/ and log in here with the same account that you are logged in with Android Studio. Now you can see your project has been added. Click on it.

open project In console

Now click on Authentication Tab -> Sign-In method -> click Google -> Enable Toggle button -> Select Email Address .

Enable Google authentication

Click Save.

Authentication save

Now open Android Studio -> Select Android -> Gradle Script -> Open build.Gradle file

Now add these two dependencies and click Sync Now.

implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.google.android.gms:play-services-auth:17.0.0'

Add dependencies

Building UI

Before we start building the interface and start coding the functionality, we need to add internet permission in the Android Manifest file. I am doing it at the very beginning because I often forget to add it and then start scratching my head that why the code is not working!

Add Internet permission in AndroidManifest.xml

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

Add permission

Enter code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".MainActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/SignIn_Button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="284dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/Sign_out"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sing out"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/SignIn_Button"
        app:layout_constraintVertical_bias="0.258" />


</androidx.constraintlayout.widget.ConstraintLayout>

Adding functionality

Enter code in MainActivity.java

package com.arslan6015.loginwithgoogle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.UserHandle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class MainActivity extends AppCompatActivity {

    private SignInButton signInButton;
    private GoogleSignInClient googleSignInClient;
    private String TAG="mainTag";
    private FirebaseAuth mAuth;
    private Button btnSignOut;
    private int RESULT_CODE_SINGIN=999;

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

        //initialization
        signInButton = findViewById(R.id.SignIn_Button);
        mAuth = FirebaseAuth.getInstance();
        btnSignOut = findViewById(R.id.Sign_out);
        btnSignOut.setVisibility(View.INVISIBLE);

        // Configure sign-in to request the user's ID, email address, and basic
        // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
        GoogleSignInOptions gso = new
                GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        // Build a GoogleSignInClient with the options specified by gso.
        googleSignInClient = GoogleSignIn.getClient(this,gso);

        //Attach a onClickListener
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signInM();
            }
        });

        //Attach a onClickListener
        btnSignOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                googleSignInClient.signOut();
                btnSignOut.setVisibility(View.INVISIBLE);
                signInButton.setVisibility(View.VISIBLE);
                Toast.makeText(MainActivity.this,"you are logged out",Toast.LENGTH_LONG).show();
            }
        });
    }

    //when the signIn Button is clicked then start the signIn Intent
    private void signInM() {
        Intent singInIntent = googleSignInClient.getSignInIntent();
        startActivityForResult(singInIntent,RESULT_CODE_SINGIN);
    }

    // onActivityResult (Here we handle the result of the Activity )
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_CODE_SINGIN) {        //just to verify the code
            //create a Task object and use GoogleSignInAccount from Intent and write a separate method to handle singIn Result.

            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }


    private void handleSignInResult(Task<GoogleSignInAccount> task) {

        //we use try catch block because of Exception.
        try {
            signInButton.setVisibility(View.INVISIBLE);
            GoogleSignInAccount account = task.getResult(ApiException.class);
            Toast.makeText(MainActivity.this,"Signed In successfully",Toast.LENGTH_LONG).show();
            //SignIn successful now show authentication
            FirebaseGoogleAuth(account);

        } catch (ApiException e) {
            e.printStackTrace();
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
            Toast.makeText(MainActivity.this,"SignIn Failed!!!",Toast.LENGTH_LONG).show();
            FirebaseGoogleAuth(null);
        }
    }

    private void FirebaseGoogleAuth(GoogleSignInAccount account) {
            AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        //here we are checking the Authentication Credential and checking the task is successful or not and display the message
        //based on that.
        mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){
                    Toast.makeText(MainActivity.this,"successful",Toast.LENGTH_LONG).show();
                    FirebaseUser firebaseUser = mAuth.getCurrentUser();
                    UpdateUI(firebaseUser);
                }
                else {
                    Toast.makeText(MainActivity.this,"Failed!",Toast.LENGTH_LONG).show();
                    UpdateUI(null);
                }
            }
        });
    }

    //Inside UpdateUI we can get the user information and display it when required
    private void UpdateUI(FirebaseUser fUser) {
        btnSignOut.setVisibility(View.VISIBLE);

        //getLastSignedInAccount returned the account
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        if (account !=null){
            String personName = account.getDisplayName();
            String personGivenName = account.getGivenName();
            String personEmail = account.getEmail();
            String personId = account.getId();

            Toast.makeText(MainActivity.this,personName + "  " + personEmail,Toast.LENGTH_LONG).show();
        }
    }
}

Running the application

Run the app and now you can see the output as shown above in the video and you can also see in Firebase console that a new user is added

Final output

I hope you have understood how the Firebase Authentication works with Google, and how you can provide the “Continue with Google” button to your Android App.

Not interested in Google Sign in? You can:

Don’t forget to ask a question. I understand many people feel being an idiot in asking a question, please don’t feel hesitation. I’ll be delighted to answer your simplest or hardest question.

 

3 thoughts on “Login with Google Using Firebase Authentication in Android Studio (Tutorial)”

Comments are closed.