Integrating Google Sign-In into Your Android App Example

Google Sign-In allow users sign in to your Android app with their existing Google account and get their profile information like name, email, profile pic and other details. The major advantage of integrating Google login is, you can provide your users quicker & easiest way of registration process.

1. Install/Update Google Play Services

Google Sign-In requires Google Play Services so go to Android SDK Manager and check if you have already installed latest version of Google Play Services.
Install/Update Google Play Services
Install/Update Google Play Services


2. Get a Configuration File 

To Integrate Google Sing In in to your Android project, you need to get configuration file  
google-services.json

To get configuration file go to Google Sign-In for Android and 
click on GET A CONFIGURATION FILE button.
Get a configuration File for Google Sign-In for Android
Get a configuration File for Google Sign In for Android

Enter App name, Android package name and select your country/region
Click on Choose and configure services button
Create or Choose an App
Create or Choose an App


To use Google Sign-In you need to provide SHA-1 of your signing certificate to generate OAuth2 client and API key for your app. Once SHA-1 Key is generated, add it and Click on ENABLE GOOGLE SIGN-IN button
Enter SHA-1 of your Signing Certificate
Enter SHA-1 of your Signing Certificate



How do I find my SHA-1?

Open your terminal or command prompt
Change the directory to the JDK bin directory
cd C:\Program Files\Java\jdk1.8.0_91\bin
Use the following command to generate SHA-1 (Replace HOMEPATH according to your system)
keytool -exportcert -list -v -alias androiddebugkey -keystore c:\users\sushil\.android\debug.keystore
-:or:-
keytool -list -v -keystore c:\users\sushil\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
While generating SHA-1 if it asks for password, enter "android"
Generate SHA1 for Google Sign-In
Generating SHA1 for Google Sign-In in Windows
More about How do I find my SHA-1

Command to generate SHA-1 in Linux/MAC
keytool -exportcert -list -v \ -alias androiddebugkey -keystore ~/.android/debug.keystore

Click on Download google-service.json button to download configuration file
Download Configuration file
Download Configuration file


3. Add Configuration file to your project

Create Project 

create project in Android Studio with same App name and Package name given while generating configuration file.

In my case
App name was GoogleSignIn and 
Package name was com.sonevalley.blogspot.googlesignin

Copy the google-services.json file you just downloaded into the app/ or mobile/ directory of your Android Studio project. In my case app/ directory is

C:\Users\Sushil\AndroidStudioProjects\GoogleLogIn\app

Add the Google Services Plugin

Add the dependency to your project level build.gradle
classpath 'com.google.gms:google-services:3.0.0'

Add the plugin to your app level build.gradle
apply plugin: 'com.google.gms.google-services'

Add Google Play Services

In your app level build.gradle add the following dependencies
dependencies {
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services-auth:9.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
}



4. Source Code

In your project create SignInActivity and make use of the source code given below
activity_signin.xml
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    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="com.blogspot.sonevalley.googlesignin.SignInActivity">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Google Sign In"
        android:textSize="22sp"
        android:textStyle="bold"/>

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:layout_below="@id/tvTitle"/>

    <ImageView
        android:id="@+id/ivProfilePic"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginTop="100dp"
        android:layout_below="@id/sign_in_button"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ivProfilePic"
        android:layout_centerHorizontal="true"
        android:textAlignment="center" />

    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:textAlignment="center"
        android:text="You are not logged in!" />

</RelativeLayout>


SignInActivity.java
package com.blogspot.sonevalley.googlesignin;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

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.sonevalley.blogspot.googlesignin.R;
import com.squareup.picasso.Picasso;

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

    private int RC_SIGN_IN = 1;
    GoogleApiClient mGoogleApiClient;
    SignInButton signInButton;

    TextView tvName;
    TextView tvStatus;
    ImageView ivProfilePic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin);
        tvName = (TextView) findViewById(R.id.tvName);
        tvStatus = (TextView) findViewById(R.id.tvStatus);
        ivProfilePic = (ImageView) findViewById(R.id.ivProfilePic);

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

        // Build a GoogleApiClient with access to the Google Sign-In API and the
        // options specified by gso.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
        signInButton.setScopes(gso.getScopeArray());
        signInButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == signInButton) {
            signIn();
        }
    }

    private void signIn() {
        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);

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        Log.d("SignInActivity", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            tvName.setText("Hello "+acct.getDisplayName());
            tvStatus.setText("Your Email: "+acct.getEmail());
            Picasso
                    .with(this)
                    .load(acct.getPhotoUrl())
                    .into(ivProfilePic);
        } else {
            //Signed out, show unauthenticated UI.
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d("MainActivity", "onConnectionFailed:" + connectionResult);
    }
}



5. Output Screens

Before Signed-In Click on Sign-In Button
Before Signed-In


Successfully Signed-In
After Signed-In

SHARE
    Blogger Comment
    Facebook Comment

1 comments:

  1. Merely this is the best blog I could locate of google. The way you make such noteworthy and alluring information accessible here is appreciable. Keep up with this tremendous work and continue updating.
    English practice App | English with experts

    ReplyDelete