Skip to content
FrugalisMinds
  • Home
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • About Us
  • Dev Tools

FrugalisMinds

  • Home
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • Spring
    • Spring Boot
    • Spring Security
    • Spring Cloud
  • About Us
  • Dev Tools

Integrate Google Sign In Into Android

October 29, 2023 by tom

Integrate Google Sign Into Android:-

We will integrate Google sign in into  Android app. Google let users sign in through their Gmail account in their Android app.Google signing we get all the user details such as profile details, image, contacts very easily and quickly.

Integrating Google sign in into your Android app lets users sign quickly without the need for the complex registration process.



Configure Google Sign in:-

In order to integrate Google Sign In we need to first go ahead and set up the project on the Google developer console. We need to add  google-services.json file to your project’s app folder. Please visit on the link here.

  1. This will take you to link where you will be prompted to enter app name and package name as shown below.
  2. Enter the project name if not create a project.
  3. Then enter the project package name as per your choice.
  4. Click on choose and now we get the next screen where we need to add our SHA1 key.

Generate SHA1 Key :-

Now we need Java keytool to generate SHA1 fingerprint so, in order to use Java keytool, you must have Java installed on your machine.Then you go to your command prompt and type the following command below to generate the SHA1 fingerprint.Its super easy.

keytool -exportcert -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore

You will get something like this as output:-

Copy SHA1 value and paste in the next screen.

Go to next and Click on download google-services.json and download the JSON file.

Create and Setup Project :

Create the New project and Enter same package name as you have configured before.

Add com.google.android.gms:play-services-auth:11.0.2 dependency to your app level build file and apply plugin ‘com.google.gms.google-services‘ on the bottom of your app level build folder.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.2'

    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Open project level build file and add following

 dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

Create activity_main.xml:-

we are adding two buttons one for SignIn and other for SignOut.

<?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:layout_height="match_parent"
    tools:context="org.cravez.in.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="120dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <Button
            android:id="@+id/signin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SignIn"
            tools:layout_editor_absoluteX="-111dp"
            tools:layout_editor_absoluteY="463dp" />

        <Button
            android:id="@+id/signout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Signout" />
    </LinearLayout>

</LinearLayout>

Configure Auth2.0 Client Id :-

you can skip this if you want to do signin just for demo purpose but, if you want to do a backend validation we need google signin to generate a token and send to our REST server which will do the validations and authentication.  This step is needed if you want to pass the currently signed-in user to a backend server, send the ID token to your backend server and validate the token on the server.Visit Google developer console  . Select the appropriate project and click on Credentials.

You see list of  OAuth 2.0 client IDs, select Web client (Auto-created for Google Sign-in) and copy the client id and store it in a string resource as

    <string name="server_clientid">Your Copied Web Client Key </string>

We are using this key when we create an object of  GoogleSignInOptions  as below in MainActivity.java

Now Open your MainActivity.java and add below set of code step by step.

In OnCreate Method add GoogleSigninoptions object create a method called signinClick() ,handleSignInResult().

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.server_clientid))
        .requestProfile()
        .requestEmail()
        .build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this, this)
       .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
       .build();
private void signInClick () {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

MainActivity.java:-

We are receiving token after the user signed in in handleSignInResult and now use this token to validate. Please visit the link here to check google implementation here .

package org.cravez.in;

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.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

public class MainActivity extends AppCompatActivity implements  GoogleApiClient.OnConnectionFailedListener{

    Button signin,signout;
    GoogleApiClient mGoogleApiClient;
    private static final int RC_SIGN_IN = 9001;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);
        signin=(Button)findViewById(R.id.signin);
        signout=(Button)findViewById(R.id.signout);
        signout.setVisibility(View.GONE);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.server_clientid))
                .requestProfile()
                .requestEmail()
                .build();

         mGoogleApiClient = new GoogleApiClient.Builder(this)
                 .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "hii", Toast.LENGTH_SHORT).show();
                signInClick();

            }
        });

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

                Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                        new ResultCallback<Status>() {
                            @Override
                            public void onResult(Status status) {
                                // [START_EXCLUDE]
                                if(status.isSuccess()){
                                    signin.setVisibility(View.VISIBLE);
                                    signout.setVisibility(View.GONE);
                                }

                                // [END_EXCLUDE]
                            }
                        });
            }
        });

    }

    private void signInClick () {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

            handleSignInResult(result);
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }



    private void handleSignInResult(GoogleSignInResult result) {

        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            String idToken = acct.getIdToken();
            Log.d("DD", idToken);
            signout.setVisibility(View.VISIBLE);
            signin.setVisibility(View.GONE);

        }
    }


}

Output:-

Download Code

Categories Android Tags Android, Google Signin Android
Custom ClassLoaders In Java With Example

Live Support

Join Our Group Of Spring and Java Experts with Avg. more than 10+ Years Of Expertise for Any Technical Support for Free .

Join Support

Recent Posts

Binary Search Java

Binary Search : Extra Care

Integrate Google Sign In Into Android

Java Custom Class Loaders

Custom ClassLoaders In Java With Example

how fat jar works

What is a Spring Boot Fat Jar File

Typescript React JS Image Upload and Preview

Mastering Typescript React JS Image Upload and Preview

How to add Days , Month   and Year  to a date  in Javascript

handle large data sizes in PostgreSQL with COPY MANAGER

handle large data sizes in PostgreSQL with COPY MANAGER

Spring Boot MongoDB Docker Example

Golang Tutorials For Beginners

Golang Tutorials For Beginners

How to Install MongoDB On CentOS 8

HashCode and Equals Method Java

java hashcode and equals method example

© 2025 FrugalisMinds • Built with Love
Privacy Policy Terms Contact
  • Privacy Policy
  • Terms
  • Contact Us
  • DnsChecker
  • Dev Tools

Last Updated on 2 years by tom