CoderzHeaven

January 22, 2016

Implementing Google Sign in – Android

How to implement Google Sign in Android Apps.

Create a new project in Android Studio and name it DemoSignIn.

1. Get Google Configuration File (google-services.json).

Follow the steps that google says and get the Configuration file.

Go to this link and get it (https://developers.google.com/identity/sign-in/android/start-integrating).

2. After that go to your root “App” directory and copy it there.

Make sure you give the exact package name for the app in which you need the Google Sign In.

Google Sign In will work only if you have entered the values incorrectly in the console.

3. Update Gradle..

Add dependencies in app:gradle.

compile 'com.google.android.gms:play-services:8.4.0'

Next we will jump into the code.

I have a layout like this with three buttons, Sign In, Sign Out and Revoke Access.

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"app:layout_behavior="@string/appbar_scrolling_view_behavior"tools:context="com.test.demosignin.MainActivity"tools:showIn="@layout/activity_main"><TextViewandroid:id="@+id/tv"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:text="Click Sign In to Continue"android:gravity="center"android:layout_margin="10dp"/><com.google.android.gms.common.SignInButtonandroid:id="@+id/sign_in_button"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/tv"android:layout_margin="10dp"/><Buttonandroid:layout_below="@+id/sign_in_button"android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/sign_out_button"android:text="Sign Out"android:layout_margin="10dp"/><Buttonandroid:layout_below="@+id/sign_out_button"android:id="@+id/revoke_button"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Revoke Access"android:layout_margin="10dp"/></RelativeLayout>


The AndroidManifest will look like this.

<?xml version="1.0" encoding="UTF-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.demosignin"><uses-permission android:name="android.permission.INTERNET" /><application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/AppTheme"><activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

The MainActivity.java

package com.test.demosignin;import android.content.Intent;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.util.Log;import android.view.View;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.google.android.gms.common.api.OptionalPendingResult;import com.google.android.gms.common.api.ResultCallback;import com.google.android.gms.common.api.Status;public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {GoogleApiClient mGoogleApiClient;privatestatic final String TAG = "Google Sign In";private static final int RC_SIGN_IN = 9001;private TextView mStatus;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);GoogleSignInOptions gso = initGoogleAPI();SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);signInButton.setSize(SignInButton.SIZE_STANDARD);signInButton.setScopes(gso.getScopeArray());signInButton.setOnClickListener(this);findViewById(R.id.sign_out_button).setOnClickListener(this);findViewById(R.id.revoke_button).setOnClickListener(this);findViewById(R.id.sign_out_button).setVisibility(View.GONE);findViewById(R.id.revoke_button).setVisibility(View.GONE);mStatus = (TextView) findViewById(R.id.tv);}@NonNullprivate GoogleSignInOptions initGoogleAPI() {// 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 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();return gso;}@Overridepublic void onStart() {super.onStart();OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);if (opr.isDone()) {// If the user's cached credentials are valid, the OptionalPendingResult will be "done"// and the GoogleSignInResult will be available instantly.Log.d(TAG, "Got cached sign-in");GoogleSignInResult result = opr.get();handleSignInResult(result);} else {// If the user has not previously signed in on this device or the sign-in has expired,// this asynchronous branch will attempt to sign in the user silently.Cross-device// single sign-on will occur in this branch.mStatus.setText("Attempting to Sign in...");opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {@Overridepublic void onResult(GoogleSignInResult googleSignInResult) {handleSignInResult(googleSignInResult);}});}}@Overridepublic void onConnectionFailed(ConnectionResult connectionResult) {Log.i(TAG, "Connection failed");}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.sign_in_button:signIn();break;case R.id.sign_out_button:signOut();break;case R.id.revoke_button:revokeAccess();break;}}private void signIn() {Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);startActivityForResult(signInIntent, RC_SIGN_IN);}private void signOut(){Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {@Overridepublic void onResult(Status status) {Log.i(TAG, "signOut Done");mStatus.setText("Signed Out.");findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);findViewById(R.id.sign_out_button).setVisibility(View.GONE);findViewById(R.id.revoke_button).setVisibility(View.GONE);}});}// [START revokeAccess]private void revokeAccess() {Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {@Overridepublic void onResult(Status status) {Log.i(TAG, "Revoke Done");mStatus.setText("Access Revoked.");findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);findViewById(R.id.sign_out_button).setVisibility(View.GONE);findViewById(R.id.revoke_button).setVisibility(View.GONE);}});}// [END revokeAccess]@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);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 acct = result.getSignInAccount();Log.i(TAG, "User Display Name : " +acct.getDisplayName());mStatus.setText("Signed in as : " + acct.getDisplayName());findViewById(R.id.sign_in_button).setVisibility(View.GONE);findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);findViewById(R.id.revoke_button).setVisibility(View.VISIBLE);} else {// Signed out, show unauthenticated UI.findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);mStatus.setText("Signed Out.");}}}

Download the complete Android Source Code from here…


NOTE : CREATE A SIGNED APK FOR RUNNING. GOOGLE SIGN IN MAY NOT WORK ON DEBUG CERTIFICATES.

Leave a Reply Cancel reply