Google Plus Sign in Integration In Android Studio Step by Step

google plus sign in integration in android studio

Today we will develop Google plus sign in integration in android studio example.

We need to put Google login integration in android programmatically to allow a user to login via their social accounts.

Google API provides in built google account login or sign in button, which we can directly use in the xml layout file.

First, check the output of Gmail or Google plus sign in integration in android studio, which is developed by demonuts.com.

 

Step 1: Create a new project in the Android Studio

First of all, make a new android studio project. When you are doing this, select “Empty Activity” as a Main Activity.

Step 2: Creating an app in Google developer console.

Watch following video, which describes the whole process to develop an app in the Google developer console.

Now here is a quick explanation of above video.

      1. Login to your Google account and open Google developer console.
      2. Click on create a project which is at left upper corner and wait till app is created.
      3. Now for configuration file click on developers.google.com
      4. Click on get configuration file button.
      5. Select your app, put package name and SHA-1 and generate JSON file.
      6. Put google-services.json file in your android studio project’s app folder.
      7. Directory will look like this
google plus login sign in integration android
google login android app folder structure

Step 3: Updating build.gradle(Project: project_name) file:

we need to add following in dependencies{} structure

 classpath 'com.google.gms:google-services:1.5.0-beta2'

and add the following

 maven { url 'https://jitpack.io' }

in the

allprojects {
    repositories {
 }
}

structure. So final code for build.gradle(Project: project_name)  will look like this: 

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'
        classpath 'com.google.gms:google-services:1.5.0-beta2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

 add internet permission between <manifest>….</manifest> tag.

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

Note: If you are targeting SDK version above 22 (Above Lollipop)  then you need to ask a user for granting runtime permissions. Check marshmallow runtime permission for more information.

Step 4: Updating build.gradle(Module:app) file

Add following code into dependencies{} 

    compile 'com.google.android.gms:play-services-auth:9.0.2'
    compile 'com.google.android.gms:play-services:9.0.2'
    compile 'com.github.androidquery:androidquery:0.26.9'

So the whole file will be:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.exampledemo.parsaniahardik.google_login_demonuts"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services-auth:9.0.2'
    compile 'com.google.android.gms:play-services:9.0.2'
    compile 'com.github.androidquery:androidquery:0.26.9'
}

Here we have added Aquery dependency. Aquery is a library which is used for fetching an image from the given URL. We will show it’s usage later to fetch profile picture. GitHub link for Aquery.

Step 5: Updating activity_main.xml file:

Add following code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.google_login_demonuts.MainActivity">

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:scaleType="fitXY"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_horizontal"
        android:id="@+id/iv"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text"
        android:textColor="#000"
        android:layout_marginTop="20dp"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="200dp"
        android:layout_marginTop="20dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_horizontal"
        android:text="Logout"
        android:id="@+id/btn"/>
</LinearLayout>

Step 6: Final code for MainActivity.java file:

package com.exampledemo.parsaniahardik.google_login_demonuts;

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

import com.androidquery.AQuery;
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 com.google.android.gms.plus.People;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

public class MainActivity extends AppCompatActivity implements  GoogleApiClient.OnConnectionFailedListener{

    private SignInButton signInButton;
    private GoogleSignInOptions gso;
    private GoogleApiClient mGoogleApiClient;
    private int SIGN_IN = 30;
    private TextView tv;
    private ImageView iv;
    private AQuery aQuery;
    private Button btn;

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

        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addApi(Plus.API)
                .build();

        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                startActivityForResult(signInIntent, SIGN_IN);
            }
        });

        tv = (TextView) findViewById(R.id.text);
        iv = (ImageView) findViewById(R.id.iv);
        btn = (Button) findViewById(R.id.btn);
        aQuery = new AQuery(this);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                        new ResultCallback<Status>() {
                            @Override
                            public void onResult(Status status) {
                                Toast.makeText(MainActivity.this, "Logout Successfully!", Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //If signin
        if (requestCode == SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            //Calling a new function to handle signin
            handleSignInResult(result);
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        //If the login succeed
        if (result.isSuccess()) {
            //Getting google account
            final GoogleSignInAccount acct = result.getSignInAccount();

            //Displaying name and email
            String name = acct.getDisplayName();
            final String mail = acct.getEmail();
            // String photourl = acct.getPhotoUrl().toString();

            final String givenname="",familyname="",displayname="",birthday="";

            Plus.PeopleApi.load(mGoogleApiClient, acct.getId()).setResultCallback(new ResultCallback<People.LoadPeopleResult>() {
                @Override
                public void onResult(@NonNull People.LoadPeopleResult loadPeopleResult) {
                    Person person = loadPeopleResult.getPersonBuffer().get(0);

                    Log.d("GivenName ", person.getName().getGivenName());
                    Log.d("FamilyName ",person.getName().getFamilyName());
                    Log.d("DisplayName ",person.getDisplayName());
                    Log.d("gender ", String.valueOf(person.getGender())); //0 = male 1 = female
                    String gender="";
                    if(person.getGender() == 0){
                        gender = "Male";
                    }else {
                        gender = "Female";
                    }

                    if(person.hasBirthday()){
                        tv.setText(person.getName().getGivenName()+" \n"+person.getName().getFamilyName()+" \n"+gender+"\n"+person.getBirthday());
                    }else {
                        tv.setText(person.getName().getGivenName()+" \n"+person.getName().getFamilyName()+" \n"+gender);

                    }
                    aQuery.id(iv).image(acct.getPhotoUrl().toString());
                   Log.d("Uriddd",acct.getPhotoUrl().toString());
                  /*   Log.d(TAG,"CurrentLocation "+person.getCurrentLocation());
                    Log.d(TAG,"AboutMe "+person.getAboutMe());*/
                    // Log.d("Birthday ",person.getBirthday());
                    // Log.d(TAG,"Image "+person.getImage());
                }
            });
        } else {
            //If login fails
            Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}

Step 7: Overview of MainActivity.java class:

  • GoogleSignInOption and GoogleApiClient are initialized.
  • An Intent to open google login android screen is written in the onClick method of signinbutton.
  • After the user enters his email id and password, the code will go into the onActivityResult() method and from there, code will redirect to the handleSignInResult() method.
  • In  handleSignInResult() method, we can get user’s information in two ways. The First way is to get information using GoogleSignInAccount class’s instance and the second way is by Person class’s instance as shown in the code snippet.
  • Aquery is used in this line:
     aQuery.id(iv).image(acct.getPhotoUrl().toString());

    as you can see, we need to pass our ImageView in id() section, and URL from which we are getting the image is passed in the image section.

Logout from Google login Android integration

We can logout user by the following code as shown in MainActivity.java

 btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                        new ResultCallback<Status>() {
                            @Override
                            public void onResult(Status status) {
                                Toast.makeText(MainActivity.this, "Logout Successfully!", Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });

If you wish to logout user from any other activity, put this in `onCreate()` method of any activity:

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();

and then override onStart() method:

 @Override
        protected void onStart() {
            super.onStart();
            mGoogleApiClient.connect();
        }

After doing this, you can put the code for logout in any button’s onClick() method as we have put in MainActivity.java.

After Google, you will need to integrate Facebook login shortly.

You can learn Facebook login integration easily step by step

Stackoverflow link for logout implementation: Logout From Google.

So it was all for this google plus sign in integration in android studio integration tutorial. Hope you have learned easily all the stuff and keep coding, keep learning. See you in the next tutorial. Thank you.

Download Source Code For Google Plus Sign in Integration in Android studio

[sociallocker]Download Demo [/sociallocker]