Android Google Plus API Login Integration Example

In this tutorial, we are going to learn how to integrate Google Plus for android application login feature. Android Google Plus Login can be an easy way to implement a login system in android application since many people are using Google Plus and besides, it takes a few clicks for a new user to login using Google+.

If you are interested in integrating Facebook SDK for Android Login, I wrote a comprehensive tutorial that explains how to integrate Facebook SDK in your android app.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android google login

Android google+ login

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidGooglePlusSignIn

Package: com.inducesmile.androidandroidgoogleplussignin

Select Empty Activity

Name the Activity – GoogleSignInActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Before we start to integrate Google Sign-In into our android app, we have to configure a Google Developers Console project and set it up in Android Studio.

Conditions for Google Sign-In for Android

A compatible Android device that runs Android 2.3 or newer and includes the Google Play Store or an emulator with an AVD that runs the Google APIs platform based on Android 4.2.2 or newer and has Google Play Services version 8.4.0 or newer.

The latest version of the Android SDK, including the SDK Tools component. The SDK is available from the Android SDK Manager in Android Studio.

A project configured to compile against Android 2.3 (Gingerbread) or newer.

The Google Play Services SDK:

In Android Studio, select Tools > Android > SDK Manager.

Scroll to the bottom of the package list and select Extras > Google Play services. The package is downloaded to your computer and installed in your SDK environment at android-sdk-folder/extras/google/google_play_services.

If you have these conditions ready, then we will head over to Android developer’s page. On this page, click on the button named – GET A CONFIGURATION FILE as shown in the image below

googleone

Enter the required information in enable Google services for your app page. Click on the Choose and configure services button as shown

googletwo

To use Google Sign-In, you’ll need to provide the SHA-1 of your signing certificate so we can create an OAuth2 client and API key for your app.

googlethree

To get the SHA-1, run the following command in Window’s command prompt

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

googlefour

Copy and paste the SHA-1 key obtain in the space provided.

Click the ENABLE GOOGLE SIGN-IN button and download the configuration file. Put the configuration file in app folder root directory of your project.

Add the Google Services plugin

The Google Services plugin for Gradle parses configuration information from the google-services.json file. Add the plugin to your project by updating your top-level build.gradle and your app-level build.gradle files as follows:

Add the dependency to your project-level build.gradle:

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

Add the plugin to your app-level build.gradle:

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

Add Google Play Services

In your app-level build.gradle file, declare Google Play Services as a dependency:

dependencies {
    classpath 'com.android.tools.build:gradle:2.0.0'
    classpath 'com.google.gms:google-services:1.5.0-beta2'
}

The dependencies section of our build.gradle contains some other libraries.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile "com.google.android.gms:play-services:8.3.0"
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

The circularImageView is use to convert user profile photo in a circular form while Picasso is a network library that is used to download user profile photo.

Now that we have finished with setting up Google Sign-in, we will move over to the code implementation of our project.

Go to the res folder, then double click on the values folder and double click on the colors.xml file and add the following lines of codes. This will holder all the colors we will use in this tutorial.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
</resources>

Now, head over to the strings.xml file and modify the content with the code below.

<resources>
    <string name="app_name">Android GooglePlus SignIn</string>
    <string name="action_logout">Logout</string>
    <string name="action_disconnect">Disconnect</string>
</resources>

The complete code for Manifest.xml file as as shown

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androidgoogleplussignin">
    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".GoogleSignInActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ProfileActivity"></activity>
    </application>
</manifest>

Let look into our project main layout file. We have created a default Activity with it‘s corresponding layout file name GoogleSignInActivity.java and activity_google_sign_in.xml when we created our project.

Open the layout file, we are going to add the Google Plus login button code. We want when a user clicks on this button it will let the user to select the Google account that will be use to login. If the user successfully login, the user profile image, email, and displayed name will be shown in the ProfileActivity page.

Open the layout file located at res > layout > activity_google_sign_in.xml and paste the code inside.

<?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"
    android:background="@drawable/background"
    tools:context="com.inducesmile.androidgoogleplussignin.GoogleSignInActivity">
    <com.google.android.gms.common.SignInButton
        android:id="@+id/google_sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

For the Activity class, we will get the instance of the login button. The button object is wired with a click event which obtain an Intent that will be use to initiate the startActivityForResult(signInIntent, RC_SIGN_IN) method.

The class will implement GoogleApiClient.OnConnectionFailedListener. We will also instantiate an object of GoogleApiClient class. The connect and disconnect method is called on this object in the Activity onStart and onStop methods.

Open the GoogleSignInActivity file, copy and paste the code inside this file.

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
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.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
public class GoogleSignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
    private static final String TAG = "GoogleSignInActivity";
    private static final int RC_SIGN_IN = 9001;
    private GoogleSignInOptions gso;
    private GoogleApiClient mGoogleApiClient;
    public static final String PROFILE_USER_ID = "USER_ID";
    public static final String PROFILE_DISPLAY_NAME = "PROFILE_DISPLAY_NAME";
    public static final String PROFILE_USER_EMAIL = "USER_PROFILE_EMAIL";
    public static final String PROFILE_IMAGE_URL = "PROFILE_IMAGE_URL";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_sign_in);
        gso = ((MyApplication) getApplication()).getGoogleSignInOptions();
        mGoogleApiClient = ((MyApplication) getApplication()).getGoogleApiClient(GoogleSignInActivity.this, this);
        SignInButton mSignInButton = (SignInButton)findViewById(R.id.google_sign_in_button);
        assert mSignInButton != null;
        mSignInButton.setSize(SignInButton.SIZE_STANDARD);
        mSignInButton.setScopes(gso.getScopeArray());
        mSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                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(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount userAccount = result.getSignInAccount();
            String userId = userAccount.getId();
            String displayedUsername = userAccount.getDisplayName();
            String userEmail = userAccount.getEmail();
            String userProfilePhoto = userAccount.getPhotoUrl().toString();
            Intent googleSignInIntent = new Intent(GoogleSignInActivity.this, ProfileActivity.class);
            googleSignInIntent.putExtra(PROFILE_USER_ID, userId);
            googleSignInIntent.putExtra(PROFILE_DISPLAY_NAME, displayedUsername);
            googleSignInIntent.putExtra(PROFILE_USER_EMAIL, userEmail);
            googleSignInIntent.putExtra(PROFILE_IMAGE_URL, userProfilePhoto);
            startActivity(googleSignInIntent);
        }
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }
    @Override
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    //hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }
    @Override
    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }
}

You will find out that we used custom Application class to make some class instance global so that we can access it from another Activity class.

Right click on your package folder, choose create new java file and name the file – MyApplication.

Let MyApplication class extends the default Application class. Also, open the Manifest file and add this line of code in application element.

android:name=".MyApplication"

Copy and paste the following code inside this class.

package com.inducesmile.androidgoogleplussignin;
import android.app.Application;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.GoogleApiClient;
public class MyApplication extends Application {
    private GoogleApiClient mGoogleApiClient;
    private GoogleSignInOptions gso;
    public AppCompatActivity activity;
    public GoogleSignInOptions getGoogleSignInOptions(){
        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        return gso;
    }
    public GoogleApiClient getGoogleApiClient(AppCompatActivity activity, GoogleApiClient.OnConnectionFailedListener listener){
        this.activity = activity;
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this.activity, listener)
                .addApi(Auth.GOOGLE_SIGN_IN_API, getGoogleSignInOptions())
                .build();
        return mGoogleApiClient;
    }
}

For the ProfileActivity page which will display login user details, we are going to create a new Activity file and I will name it ProfileActivity.java with it’s corresponding layout file.

The layout file – activity_profile.xml located at res > layout > activity_profile.xml will contain two TextView and a custom circular ImageView widgets.

Open the layout file, add the following code inside the file.

<?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.inducesmile.androidgoogleplussignin.ProfileActivity">
    <de.hdodenhof.circleimageview.CircleImageView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/profile_image"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="80dp"
        app:civ_border_width="2dp"
        app:civ_border_color="@color/colorPrimaryDark"/>
    <TextView
        android:id="@+id/profile_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/profile_image"
        android:layout_marginTop="16dp"
        android:text="@string/app_name"
        android:textSize="20dp"
        android:textStyle="bold"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/profile_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/profile_name"
        android:layout_marginTop="8dp"
        android:text="@string/app_name"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

For the ProfileActivity page, we will get the instances of our widget controls and set the values passed through the Intent object to the Views.

You will see that we are making use of the Picasso Library to download the user profile photo using the image path.

Open the ProfileActivity class, add the following code inside the class.

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.android.gms.auth.api.Auth;
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;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
    private static final String TAG = "ProfileActivity";
    private GoogleApiClient mGoogleApiClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        mGoogleApiClient = ((MyApplication) getApplication()).getGoogleApiClient(ProfileActivity.this, this);
        CircleImageView profilePhoto = (CircleImageView)findViewById(R.id.profile_image);
        TextView profileUsername = (TextView)findViewById(R.id.profile_name);
        TextView profileEmail = (TextView)findViewById(R.id.profile_email);
        String profileDisplayName = returnValueFromBundles(GoogleSignInActivity.PROFILE_DISPLAY_NAME);
        String profileUserEmail = returnValueFromBundles(GoogleSignInActivity.PROFILE_USER_EMAIL);
        String profileImageLink = returnValueFromBundles(GoogleSignInActivity.PROFILE_IMAGE_URL);
        Picasso.with(ProfileActivity.this).load(profileImageLink).into(profilePhoto);
        assert profileUsername != null;
        profileUsername.setText(profileDisplayName);
        assert profileEmail != null;
        profileEmail.setText(profileUserEmail);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.profile, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_logout) {
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            Intent login = new Intent(ProfileActivity.this, GoogleSignInActivity.class);
                            startActivity(login);
                            finish();
                        }
                    });
            return true;
        }
        if(id == R.id.action_disconnect){
            Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            Intent login = new Intent(ProfileActivity.this, GoogleSignInActivity.class);
                            startActivity(login);
                            finish();
                        }
                    });
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    private String returnValueFromBundles(String key){
        Bundle inBundle = getIntent().getExtras();
        String returnedValue = inBundle.get(key).toString();
        return returnedValue;
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }
    @Override
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }
    @Override
    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }
}

A login user should have an option to logout or revoke access, we will implement this two features using the menu action views.

Create a new folder and new it menu if it has not been created already. The location for this folder is in res > menu. Right click on the menu folder to create a menu resource file. Name this file profile.xml or anything you like. Open this file and add the following code inside the file.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_logout"
        android:orderInCategory="100"
        android:title="@string/action_logout"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_disconnect"
        android:orderInCategory="101"
        android:title="@string/action_disconnect"
        app:showAsAction="never"/>
</menu>

This menu resource file is inflated in onCreateOptionMenu() method of the ProfileActivity class

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.profile, menu);
    return true;
}

when any of the menu action view is click, we will implement the logout and access revoke code in onOptionsItemSelected(MenuItem item) method of the ProfileActivity class.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_logout) {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        Intent login = new Intent(ProfileActivity.this, GoogleSignInActivity.class);
                        startActivity(login);
                        finish();
                    }
                });
        return true;
    }
    if(id == R.id.action_disconnect){
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        Intent login = new Intent(ProfileActivity.this, GoogleSignInActivity.class);
                        startActivity(login);
                        finish();
                    }
                });
        return true;
    }
    return super.onOptionsItemSelected(item);
}

This brings us to the end of this tutorial. I hope that you have learn something. The next tutorial will be on using twitter account for android login system.

I have a complete Android login source codes with advance features and admin back-end with user login details that comprises of Android Facebook Login, Android Twitter Login, Android Google Plus Login, Android Login and Registration with Php and MySql, Android Login with Firebase. It sells for $3.

Kindly contact me if you need it. I offer 24 – 7 support for smooth integration in your application.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

OTHER INTERESTING POSTS:

Add a Comment