Skip to content
  • android
  • Flutter
  • Kotlin
  • Firebase
  • Laravel
Droidmonk
Learn Android with Java and Kotlin
 
  • android
  • Flutter
  • Kotlin
  • Firebase
  • Laravel
Home Basics Step by step guide to Implement Google Login in Android .
Basics, Login

Step by step guide to Implement Google Login in Android .

Integration of social login is one of the most common tasks in app development , whether it is a mobile app or a website. Social login makes it easier for the user to login and try the app . Thus in this post we’ll learn to implement google login for android .

The steps involved are :
    • 1. Create a new android project
    • 2. Create and configure Google Api console project and get the configuration file
      a.

      To create a google api console project click here

      b.

      Now enter a project name and the package (i.e. com.droidmonk.googlelogin) of you app. Select your country and click the blue button to continue.

      c.

      In the next screen select Google Sign-In and you’ll be asked to enter SHA-1 value of your signing certificate. Lets get it (we are getting the SHA-1 for debug certificate only for now)-
      -On windows :Enter “keytool -exportcert -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore” on command prompt.
      -On Linux or MAC : Enter “keytool -exportcert -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore” on the terminal.
      -Now you’ll be asked for the Keystore Password ,enter “android” (that is the default password for debug keystore)
      -Find out the value for SHA-1 from the result

      d.

      Now enter the SHA-1 and click the button to proceed.

      e.

      There is a big blue button named “Download google-services.json” , click to get the configuration file.

      f.

      Put the google-services.json file inside /app directory of the project

    • 3. Set up the android studio project to integrate google login
      a.

      Add the google services plugin to the project-level build.gradle

       dependencies {
      classpath 'com.android.tools.build:gradle:2.3.3'
      classpath 'com.google.gms:google-services:3.0.0'
      }
      b.

      Add the plugin to app-level build.gradle

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

      Add google account login api of goolge play services api as dependency in the app-level build.gradle

      dependencies {
      compile 'com.google.android.gms:play-services-auth:10.2.0'
      }
    • 4. Create a GoogleSignInOptions object (inside onCreate of MainActivity) to specify the information we need from google api.

      Here we’ll create the object with DEFAULT_SIGN_IN parameter – this gives us the.build(); users’ id and basic profile information.
      GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build();

      This cofiguration does not give us the user’s email, for email we need to request it while creation GoogleSignInOptions object.

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

       

    • 5. Create a GoogleApiClient object with the the GoogleSignInOptions object created above, this will be used to access Google Sign-In api.
      	       mGoogleApiClient=new GoogleApiClient.Builder(this)
                      .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                      .build();
      
      
    • 6. Add sign-in button to our MainActivity’s layout file (activity_main.xml) and set action to it

      Inside MainActivity add a onClickListener to this button, and handle onLCick action on it.
      – Prompt the user to select a google accout
      For this purpose we need an Intent object which we can get from GoogleSignInApi as
      Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);

      And start this intent with startActivityForResult()
      startActivityForResult(signInIntent, RC_SIGN_IN);

      The second parameter is a constant integer which we’ll use to identify the request in onActivityResult() .

7. Handle the sing-in result inside onActivityResult()

A GoogleSignInAccount holds the basic information of a signed in google user, here we can get one from a GoogleSignInResults object.
GoogleSignInApi has a method getSignInResultFromIntent(Intent data) to help us retrieve the GoogleSignInResults from the intent of onActivityResult(int requestCode, int resultCode, Intent data).
Lets get it as show below:
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

The following statement gives us the GoogleSignInAccount instance holding the users information in case of a succesful login , and null in case of failure.
[cc lang=”java”]GoogleSignInAccount account=result.getSignInAccount();[/cc]

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

			        if(requestCode==REQ_CODE_GOOGLE_SIGN_IN )
			        {
						/*Handle sign in*/

				     	  /*get sign in result*/
				            GoogleSignInResult result=Auth.GoogleSignInApi.getSignInResultFromIntent(data);

				            /*check if logged in*/
				            if(result.isSuccess())
				            {
				                /*Successfully logged in */
				                GoogleSignInAccount account=result.getSignInAccount();
				                Toast.makeText(this,"Login success:"+account.getDisplayName(),Toast.LENGTH_LONG).show();
				            }
				            else
				            {
				                /*Failed to log in*/
				                Toast.makeText(this,"Login failure",Toast.LENGTH_LONG).show();
				            }
			        }
			    }
package com.droidmonk.googlelogin;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
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.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity {

    private static final int REQ_CODE_GOOGLE_SIGN_IN = 1;

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


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

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

        SignInButton btn= (SignInButton) findViewById(R.id.google_login);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                startActivityForResult(intent,REQ_CODE_GOOGLE_SIGN_IN);
            }
        });

    }

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

        if(requestCode==REQ_CODE_GOOGLE_SIGN_IN )
        {
            /*get sign in result*/
            GoogleSignInResult result=Auth.GoogleSignInApi.getSignInResultFromIntent(data);

            /*check if logged in*/
            if(result.isSuccess())
            {
                /*Successfully logged in */
                GoogleSignInAccount account=result.getSignInAccount();
                Toast.makeText(this,"Login success:"+account.getDisplayName(),Toast.LENGTH_LONG).show();
            }
            else
            {
                /*Failed to log in*/
                Toast.makeText(this,"Login failure",Toast.LENGTH_LONG).show();
            }
        }
    }
}
<?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: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.droidmonk.googlelogin.MainActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/google_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.droidmonk.googlelogin"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.android.gms:play-services-auth:10.2.0'
}
apply plugin: 'com.google.gms.google-services'
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
Create Tabs using ViewPager , TabLayout and FragmentPagerAdapter in Android
Firebase Authentication with Google Sign in

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




Recent Posts

  • Middleware to verify ownership
  • Password reset
  • Email Verification
  • Delete a product ad
  • Edit a product ad

Categories

  • android
  • Basics
  • Firebase
  • Flutter
  • jetpack
  • Kotlin
  • Laravel
  • Login
  • Uncategorized
Back to Top
©droidmonk.com
Powered by Fluida & WordPress.