How to integrate Google plus sign in into your Android app

Hello there, in this tutorial we will describe you how to integrate Google plus sign in into your Android app. Here, Google Plus sign-in lets users to sign in into your Android app with their existing Google Account. Here we build a sample Google Login app which will integrate Google Login and retrieve user profile.

Before we start, let’s see the prerequisites we need to develop the application.

Prerequisites

The requirements that we need are.

1. Android studio on your pc.

2. The latest version of the Android SDK manager including the SDK tools component.

3. The project must be configured to compile against Android 2.3 (Gingerbread) on newer.

4. Google Play Services should be installed in the Android SDK environment.

5. A real time android device configured with Android Studio.

6. A compatible Android device that runs on Android 2.3 or newer and includes the Google Play Store or Emulator with an AVD that runs the Google API’s platform based on 4.2.2 or newer and has a Google Play Services version 8.3.3 or newer

Creating a new Project

To create a new project in Android, follow the steps as stipulated below.

1. Open your Android Studio

2. Go to File menu-> New -> New Project

3. Enter Application Name: GoogleSignIn

4. Company domain: Your Package Name

5. Click on Enter button.

6. Click on next button.

7. Here Minimum SDK is Android 4.4 (KitKat).

8. Again click on ‘Next’ button.

9. Select Empty Activity and click on ‘Next’ button.

10. Enter Activity name: LoginActivity and click ‘Finish’ button.

It will create a new project with the name GoogleSignIn.

To install / Update Google Play Services:

First, we need to download the Google Play Services in Android SDK Manager.

1. In Your Project GoogleSignIn.

2. Go to Tools -> Android ->SDK Manager

3. Go to the bottom of the package list and select Extras> Google Play Services.

This package is downloaded to your computer and installed in your SDK environment at android-sdk-folder/extras/google/google_play_services.

Get a Configuration File:

The configuration File provides service specifically for your app. Go to Google Developer’s Page link.

1. Enter App name: GoogleSignIn.

2. Click on “Choose and configure services”

3. Select “Google Sign-in”.

Generate SHA-1

1. To use Google plus services, we need to enable the Google Plus API on google console and we need to register our digitally signed.

2. Run the below command to generate SHA-1 in windows command prompt.

keytool -list -v -keystore “%USERPROFILE%\.android\debug.keystore” -alias androiddebugkey -storepass android -keypass android

3. Copy the SHA-1  generated text in your terminal.

4. Paste the generated SHA-1 to Google Developers page.

5. Click on “ENABLE GOOGLE SIGN-IN”.

6. Click on “CONTINUE TO GENERATE CONFIGURATION FILE”.

7. Click on “Download google-services.json”.

8. Copy the file “google-services.json” that you just downloaded. and add that file into your app as shown below figure.

Android Manifest.xml

1. Open the Android Manifest file

2. In our application, we are using the internet to sign in with google so, for this reason we need to add required internet permissions to the android manifest file. so, please add the below code.

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

Adding Dependencies

1. Add the dependency to project level build.gradle.

classpath ‘com.google.gms:google-services:3.0.0’

2. Add the plugin to your app level build.gradle.

apply plugin: 'com.google.gms.google-services'

dependencies {
    compile 'com.google.android.gms:play-services-auth:9.0.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
}

Creating UI:

In this Application, we are creating only one UI Screen.

Open layout file in your app as app/res/layout/activity_login.xml and paste the below code.

activity_login.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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.loginworks.googlesignin.LoginActivity">

<LinearLayout
    android:id="@+id/profile_layout"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="20dp">
    <ImageView
        android:id="@+id/image"
        android:layout_gravity="center"
        android:layout_width="90dp"
        android:layout_height="wrap_content"
        android:src="@drawable/profile"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="15dp">
        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/name"
            android:textSize="15sp"
            />
        <TextView
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/email"
            android:textSize="15sp"/>

    </LinearLayout>
</LinearLayout>

<com.google.android.gms.common.SignInButton
    android:id="@+id/signInButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="150dp"/>

    <Button
        android:id="@+id/signOutButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:text="Sign Out"
        />
</LinearLayout>

Strings.xml:

<resources>
    <string name = "app_name">GoogleSignIn</string>
    <string name = "name">Name</string>
    <string name = "email">Email</string>
</resources>

LoginActivity:

Open LoginActivity file, copy and paste the below code inside the file.

package com.loginworks.googlesignin;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.bumptech.glide.Glide;
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.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener,
        GoogleApiClient.OnConnectionFailedListener {

    private TextView name_txt, email_txt;
    private SignInButton btnSignIn;
    private Button btnSignOut;
    private ImageView image;
    private GoogleApiClient mGoogleApiClient;
    private LinearLayout profileLayout;
    private  static final int REQ_CODE = 9000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        name_txt = (TextView) findViewById(R.id.name);
        email_txt = (TextView) findViewById(R.id.email);
        btnSignIn = (SignInButton) findViewById(R.id.signInButton);
        btnSignOut = (Button) findViewById(R.id.signOutButton);
        image = (ImageView) findViewById(R.id.image);
        profileLayout = (LinearLayout) findViewById(R.id.profile_layout);

        profileLayout.setVisibility(View.GONE);
        btnSignOut.setVisibility(View.GONE);

        btnSignIn.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
        btnSignIn.setSize(SignInButton.SIZE_STANDARD);
        btnSignIn.setScopes(gso.getScopeArray());

    }

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

    }

    @Override
    public void onClick(View v) {

        int id = v.getId();

        switch(id){

            case R.id.signInButton:
                signIn();

            case R.id.signOutButton:
                signOut();
        }
    }

    public void signIn(){

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, REQ_CODE);
    }

    public void signOut(){

        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                updateUI(false);
            }
        });
    }

     public void handleResult(GoogleSignInResult result) {

         if(result.isSuccess()){
             GoogleSignInAccount account = result.getSignInAccount();
             String name = account.getDisplayName();
             String email = account.getEmail();
             String img_url = account.getPhotoUrl().toString();

             name_txt.setText(name);
             email_txt.setText(email);
             Glide.with(this).load(img_url).into(image);
             updateUI(true);

         }
         else
             updateUI(false);
     }

     public void updateUI(boolean isLogin){

         if(isLogin){
             profileLayout.setVisibility(View.VISIBLE);
             btnSignIn.setVisibility(View.GONE);
             btnSignOut.setVisibility(View.VISIBLE);
         }
         else{
             profileLayout.setVisibility(View.GONE);
             btnSignIn.setVisibility(View.VISIBLE);
             btnSignOut.setVisibility(View.GONE);
         }
     }

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

        if(requestCode == REQ_CODE){
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleResult(result);
        }
    }
}

1. Here in our class LoginActivity extends from AppCompactActivity and implements from View.OnClickListener and
GoogleApiClient.OnConnectionFailedListener.

2. signIn() function performs Google sign-in and signOut() function is used to logout from the Google account

3. The app builds a GoogleSignInClient by specifying the sign-in options it needs. when we click the sign-in button, it executes the signInIntent, which prompts the user to sign-in with Google account.

// 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)
        .requestEmail()
        .build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

Test the App

Now, it’s time to test the app by using Emulator or Mobile device where you are already using your Google/Gmail account, and you should be able to sign in to the Android application using Google sign-in.

Result Screens

1. Here you can see the outcome of the screens.

2. It is the first screen that you see when you open the app, which is having one button as Sign in

3. When you click on the sign in button it will prompt like this.

4. When you select the existed account it will show the name and email of that account as shown below.

5. When you click on the sign out button it will take you back to the sign in.

Conclusion

This brings us to the end of this tutorial and I hope that this will be useful for you to integrate the Google sign-in your android app, Keep following us for more informative Blogs. Thank you!

Latest posts by Rahul Huria (see all)

Leave a Comment