Integrating Google Plus Sign In into your Android Application

With Google+ Platform for Android, you can allow application users to sign in with their existing Google Plus accounts. It helps you in knowing your end users and prviding them better enriched experience in your application. As soon as user allows your app to use Google Plus Sign In, you can easily get info about user and people in users circles. You can also take access to post on Google Plus on users behalf. Overall, it is quick and easy way to engage end users in your application.

For integrating Google Plus Sign In into your Android Application, we need to complete below steps.

1. Enable Google+ API on Developers Console and create credentials for your application authentication

2. Configuring Google Play Services in Eclipse

3. Create Android Application with Google Plus Sign

1. Configuring Google Developers Console

1.1 Go to Google Developers Console.

1.2 If you don’t have any existing projects, Create Project.

1.3 Select your project, navigate to APIs & auth -> APIs on left sidebar. Browse for Google+ API and turn ON its status by accepting terms and conditions. Do not close developers console yet, we will use it to generate authentication key in next 2 steps.

1.4 Generate SHA1 fingerprint using java keytool utility

Open your command prompt and execute the below mentioned command to generate SHA-1 fingerprint. If keytool command is not recognized, you can find it in bin directory of installed jre. In my case it is located at “C:\Program Files\Java\jre7\bin”.

[java] keytool -list -v -keystore “%USERPROFILE%\.android\debug.keystore” -alias androiddebugkey -storepass android -keypass android
[/java]

Note down SHA1 from output of above command. We will use it in next step for generating authentication key. FD:0E:04:E9:99:28:B9:3D:E7:AC:75:AF:6E:2B:F6:E7:CD:EE:CA:96 is generated in my case.

1.5 Navigate to APIs & auth -> Credentials, Create new Client ID under OAuth.

1.6 In application type selection dialog, choose Installed Application and press configure consent screen.

1.7 It will ask to Configure consent screen if not configured before. Fill necessary information and save. It will redirect you back to Client ID creation page.

1.8 In Client ID generation page, mention your application package name and SHA1 fingerprint generated previously. I have used is pkg name “com.androidsrc.googleplusdemo“. Enable deep linking option and click Create Client Id.

You will get client id corresponding to your application package name and SHA1 fingerprint. Note down this CLIENT ID. We will use this in our android application project.

2. Configuring Google Play Services in Eclipse

2.1 For Google+ integration, Google Play Services library is required to be added in project. Go to eclipse menu Window -> Android SDK Manager -> Extras. Install Google Play Services if not already installed. Update it if any latest version is available.

2.2 Import this library project to Eclipse. It will be downloaded to sdk\extras\google\google_play_services\libproject\google-play-services_lib.

3. Create Android Application with Google+ Login

3.1 Create new Android Application Project in Eclipse. Make sure to mention package name same as used while creating Client Id on Developers Console.

3.2 Add Google Play Services Project as library for your application. Open project properties and add Google Play Services as library.

3.3 Preparing Application Manifest file

Add follwing permissions to your AndroidManifest.xml file.

android.permission.INTERNET– For accessing Internet

android.permission.GET_ACCOUNTS – For accessing accounts configured on device

android.permission.USE_CREDENTIALS – To request authtokens from the AccountManager

Add meta-data for Google Play Services, it specifies google play services version with which your application was build.

[xml] <meta-data
android:name=”com.google.android.gms.version”
android:value=”@integer/google_play_services_version” />
[/xml]

Final manifest file will be as below.

[xml] <?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.androidsrc.googleplusdemo”
android:versionCode=”1″
android:versionName=”1.0″ >

<uses-sdk
android:minSdkVersion=”14″
android:targetSdkVersion=”21″ />

<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.GET_ACCOUNTS” />
<uses-permission android:name=”android.permission.USE_CREDENTIALS” />

<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”.MainActivity”
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>

<meta-data
android:name=”com.google.android.gms.version”
android:value=”@integer/google_play_services_version” />
</application>

</manifest>
[/xml]

3.4 Preparing main activity layout

We will create a simple layout which will have Sign In, Sign Out, Share on Google+, revoke access and Show User Info views. We will use FrameLayout as parent view which will have two children layout views for displaying user controls and user information. Modify activity_main.xml as below.

[xml] <FrameLayout 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:paddingLeft=”25dp”
android:paddingRight=”25dp”
tools:context=”com.androidsrc.googleplusdemo.MainActivity” >

<LinearLayout
android:id=”@+id/user_options_layout”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >

<com.google.android.gms.common.SignInButton
android:id=”@+id/sign_in_button”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp” />

<Button
android:id=”@+id/sign_out_button”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:enabled=”false”
android:text=”Sign Out” />

<Button
android:id=”@+id/show_userinfo_button”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:enabled=”false”
android:text=”Show User Info” />

<Button
android:id=”@+id/share_post_button”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:enabled=”false”
android:text=”Share post on Google+” />

<Button
android:id=”@+id/share_media_button”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:enabled=”false”
android:text=”Share media files on Google+” />

<Button
android:id=”@+id/revoke_access_button”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:enabled=”false”
android:text=”Revoke User Permissions” />
</LinearLayout>

<LinearLayout
android:id=”@+id/user_info_layout”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:visibility=”invisible” >

<ImageView
android:id=”@+id/user_profile_pic”
android:layout_width=”100dp”
android:layout_height=”100dp”
android:layout_gravity=”center_horizontal”
android:layout_marginTop=”20dp”
android:scaleType=”fitCenter” />

<TextView
android:id=”@+id/user_name”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp” />

<TextView
android:id=”@+id/user_email”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp” />

<TextView
android:id=”@+id/user_tagLine”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:visibility=”gone” />

<TextView
android:id=”@+id/user_aboutme”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:visibility=”gone” />

<TextView
android:id=”@+id/user_birthday”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:visibility=”gone” />

<TextView
android:id=”@+id/user_location”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:visibility=”gone” />

<Button
android:id=”@+id/user_options_button”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”20dp”
android:text=”Show User Options” />
</LinearLayout>

</FrameLayout>
[/xml]

Final Application UI

3.5 Preparing launcher activity source code

For using Google+ api, we need to create GoogleApiClient which will provide access to api type Plus.API with scope Plus.SCOPE_PLUS_LOGIN. We need to build GoogleApiClient for first-time sign-in and after revoking users’ access.

[java] /**
* API to return GoogleApiClient Make sure to create new after revoking
* access or for first time sign in
*
* @return
*/
private GoogleApiClient buildGoogleAPIClient() {
return new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
[/java]

Connection should be initiated in onStart() to ensure that connection request is made. Disconnect any existing connection while exiting activity in onStop().

[java] @Override
protected void onStart() {
super.onStart();
// make sure to initiate connection
mGoogleApiClient.connect();
}

@Override
protected void onStop() {
super.onStop();
// disconnect api if it is connected
if (mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
[/java]

MainActivity.java will implement following interfaces.

ConnectionCallbacks – Provides callbacks that are called when the client is connected or disconnected from the service. Most applications implement onConnected(Bundle) to start making requests.

As soon as we get connection success callback, we can update our UI components.

[java] /**
* Callback for GoogleApiClient connection success
*/
@Override
public void onConnected(Bundle connectionHint) {
mSignInClicked = false;
Toast.makeText(getApplicationContext(), “Signed In Successfully”,
Toast.LENGTH_LONG).show();

processUserInfoAndUpdateUI();

processUIUpdate(true);

}
[/java]

OnConnectionFailedListener – Provides callbacks for scenarios that result in a failed attempt to connect the client to the service

In case we have connection failure, we will handle it if it can be resolved and try to attempt for connection request again.

[java] /**
* Callback for GoogleApiClient connection failure
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
ERROR_DIALOG_REQUEST_CODE).show();
return;
}
if (!mIntentInProgress) {
mConnectionResult = result;

if (mSignInClicked) {
processSignInError();
}
}

}

/**
* Callback for suspension of current connection
*/
@Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();

}
[/java]

OnClickListener – Callback for view onClick events

If everything goes well with our connection request, our UI will be update. We will check handing of all view click events one by one.

[java] /**
* Handle Button onCLick Events based upon their view ID
*/
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.sign_in_button:
processSignIn();
break;
case R.id.sign_out_button:
processSignOut();
break;
case R.id.show_userinfo_button:
userOptionsLayout.setVisibility(View.INVISIBLE);
userInfoLayout.setVisibility(View.VISIBLE);
break;
case R.id.share_post_button:
processSharePost();
break;
case R.id.share_media_button:
processShareMedia();
break;
case R.id.revoke_access_button:
processRevokeRequest();
break;
case R.id.user_options_button:
userInfoLayout.setVisibility(View.INVISIBLE);
userOptionsLayout.setVisibility(View.VISIBLE);
break;
}

}
[/java]

Sign In Google+

If user taps SignInButton, we check it is not already connecting then initiate connection request.

[java] /**
* API to handler sign in of user If error occurs while connecting process
* it in processSignInError() api
*/
private void processSignIn() {

if (!mGoogleApiClient.isConnecting()) {
processSignInError();
mSignInClicked = true;
}

}

/**
* API to process sign in error Handle error based on ConnectionResult
*/
private void processSignInError() {
if (mConnectionResult != null &amp;&amp; mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this,
SIGN_IN_REQUEST_CODE);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
[/java]

Sign Out Google+

If user signed in successfully, you will have option to sign out current user. We need to remove default account setup with Google Play Service for our application. Making subsequent calls to connect() will allow user to select a different account.

[java] /**
* API to handle sign out of user
*/
private void processSignOut() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
processUIUpdate(false);
}

}
[/java]

Sharing Post on Google+

For processing, users request to share post on Google+. We will use PlusShare.Builder to build content of our post and share intent. Retrieved share intent can be used to launch Google+ post share activity.

[java] /**
* API to process post share request Use PlusShare.Builder to create share
* post.
*/
private void processSharePost() {
// Launch the Google+ share dialog with attribution to your app.
Intent shareIntent = new PlusShare.Builder(this).setType(“text/plain”)
.setText(“Google+ Demo http://cs2guru.com”)
.setContentUrl(Uri.parse(“http://cs2guru.com”)).getIntent();

startActivityForResult(shareIntent, 0);

}
[/java]

Sharing Media on Google+

If user opts for sharing media files with Google+ post, we will start activity with intent action set as Intent.ACTION_PICK. Make sure to specify mime type for your media. After completion of media pick request, we will create share post wit PlusShare.Buidler in onActivityResult() callback based upon result code.

[java] /**
* API to process media post request start activity with MIME type as video
* and image
*/
private void processShareMedia() {
Intent photoPicker = new Intent(Intent.ACTION_PICK);
photoPicker.setType(“video/*, image/*”);
startActivityForResult(photoPicker, PICK_MEDIA_REQUEST_CODE);

}

/**
* Handle results for your startActivityForResult() calls. Use requestCode
* to differentiate.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_MEDIA_REQUEST_CODE) {
// If picking media is success, create share post using
// PlusShare.Builder
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
ContentResolver cr = this.getContentResolver();
String mime = cr.getType(selectedImage);

PlusShare.Builder share = new PlusShare.Builder(this);
share.setText(“Hello from AndroidSRC.net”);
share.addStream(selectedImage);
share.setType(mime);
startActivityForResult(share.getIntent(),
SHARE_MEDIA_REQUEST_CODE);
}
}
}
[/java]

Revoke Google+ Granted Permissions

If user opts for signing out of your application, For next sign in request user will not be prompted to grant access until permissions are revoked. For revoking permissions, we will remove the default account set in Google Play services for our app and call revokeAccessAndDisconect() api. After this user will be prompted to agree access for next sign.

[java] /**
* API to revoke granted access After revoke user will be asked to grant
* permission on next sign in
*/
private void processRevokeRequest() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback() {
@Override
public void onResult(Status arg0) {
Toast.makeText(getApplicationContext(),
“User permissions revoked”,
Toast.LENGTH_LONG).show();
mGoogleApiClient = buildGoogleAPIClient();
mGoogleApiClient.connect();
processUIUpdate(false);
}

});

}

}
[/java]

Complete source code for MainActivity.java

[java] package com.androidsrc.googleplusdemo;

import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.PlusShare;
import com.google.android.gms.plus.Plus.PlusOptions;
import com.google.android.gms.plus.model.people.Person;

public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {

private static final int PICK_MEDIA_REQUEST_CODE = 8;
private static final int SHARE_MEDIA_REQUEST_CODE = 9;
private static final int SIGN_IN_REQUEST_CODE = 10;
private static final int ERROR_DIALOG_REQUEST_CODE = 11;

// layout for showing user control buttons
private LinearLayout userOptionsLayout;
// layout for showing signed in user info
private LinearLayout userInfoLayout;

private ImageView userProfilePic;
private TextView userName;
private TextView userEmail;
private TextView userLocation;
private TextView userTagLine;
private TextView userAboutMe;
private TextView userBirthday;

Button signOutButton;
Button userInfoButton;
Button sharePostButton;
Button shareMediaButton;
Button revokeAccessButton;

// For communicating with Google APIs
private GoogleApiClient mGoogleApiClient;
private boolean mSignInClicked;
private boolean mIntentInProgress;
// contains all possible error codes for when a client fails to connect to
// Google Play services
private ConnectionResult mConnectionResult;

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

findViewById(R.id.sign_in_button).setOnClickListener(this);
signOutButton = (Button) findViewById(R.id.sign_out_button);
signOutButton.setOnClickListener(this);
userInfoButton = (Button) findViewById(R.id.show_userinfo_button);
userInfoButton.setOnClickListener(this);
sharePostButton = (Button) findViewById(R.id.share_post_button);
sharePostButton.setOnClickListener(this);
shareMediaButton = (Button) findViewById(R.id.share_media_button);
shareMediaButton.setOnClickListener(this);
revokeAccessButton = (Button) findViewById(R.id.revoke_access_button);
revokeAccessButton.setOnClickListener(this);
findViewById(R.id.user_options_button).setOnClickListener(this);

userOptionsLayout = (LinearLayout) findViewById(R.id.user_options_layout);
userInfoLayout = (LinearLayout) findViewById(R.id.user_info_layout);

userProfilePic = (ImageView) findViewById(R.id.user_profile_pic);
userName = (TextView) findViewById(R.id.user_name);
userEmail = (TextView) findViewById(R.id.user_email);
userLocation = (TextView) findViewById(R.id.user_location);

// Initializing google plus api client
mGoogleApiClient = buildGoogleAPIClient();
}

/**
* API to return GoogleApiClient Make sure to create new after revoking
* access or for first time sign in
*
* @return
*/
private GoogleApiClient buildGoogleAPIClient() {
return new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}

@Override
protected void onStart() {
super.onStart();
// make sure to initiate connection
mGoogleApiClient.connect();
}

@Override
protected void onStop() {
super.onStop();
// disconnect api if it is connected
if (mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}

/**
* Handle Button onCLick Events based upon their view ID
*/
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.sign_in_button:
processSignIn();
break;
case R.id.sign_out_button:
processSignOut();
break;
case R.id.show_userinfo_button:
userOptionsLayout.setVisibility(View.INVISIBLE);
userInfoLayout.setVisibility(View.VISIBLE);
break;
case R.id.share_post_button:
processSharePost();
break;
case R.id.share_media_button:
processShareMedia();
break;
case R.id.revoke_access_button:
processRevokeRequest();
break;
case R.id.user_options_button:
userInfoLayout.setVisibility(View.INVISIBLE);
userOptionsLayout.setVisibility(View.VISIBLE);
break;
}

}

/**
* API to update layout views based upon user signed in status
*
* @param isUserSignedIn
*/
private void processUIUpdate(boolean isUserSignedIn) {
if (isUserSignedIn) {
signOutButton.setEnabled(true);
userInfoButton.setEnabled(true);
sharePostButton.setEnabled(true);
shareMediaButton.setEnabled(true);
revokeAccessButton.setEnabled(true);
} else {
signOutButton.setEnabled(false);
userInfoButton.setEnabled(false);
sharePostButton.setEnabled(false);
shareMediaButton.setEnabled(false);
revokeAccessButton.setEnabled(false);
}
}

/**
* Handle results for your startActivityForResult() calls. Use requestCode
* to differentiate.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SIGN_IN_REQUEST_CODE) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}

mIntentInProgress = false;

if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
} else if (requestCode == PICK_MEDIA_REQUEST_CODE) {
// If picking media is success, create share post using
// PlusShare.Builder
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
ContentResolver cr = this.getContentResolver();
String mime = cr.getType(selectedImage);

PlusShare.Builder share = new PlusShare.Builder(this);
share.setText(“Hello from AndroidSRC.net”);
share.addStream(selectedImage);
share.setType(mime);
startActivityForResult(share.getIntent(),
SHARE_MEDIA_REQUEST_CODE);
}
}
}

/**
* API to revoke granted access After revoke user will be asked to grant
* permission on next sign in
*/
private void processRevokeRequest() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback() {
@Override
public void onResult(Status arg0) {
Toast.makeText(getApplicationContext(),
“User permissions revoked”,
Toast.LENGTH_LONG).show();
mGoogleApiClient = buildGoogleAPIClient();
mGoogleApiClient.connect();
processUIUpdate(false);
}

});

}

}

/**
* API to process media post request start activity with MIME type as video
* and image
*/
private void processShareMedia() {
Intent photoPicker = new Intent(Intent.ACTION_PICK);
photoPicker.setType(“video/*, image/*”);
startActivityForResult(photoPicker, PICK_MEDIA_REQUEST_CODE);

}

/**
* API to process post share request Use PlusShare.Builder to create share
* post.
*/
private void processSharePost() {
// Launch the Google+ share dialog with attribution to your app.
Intent shareIntent = new PlusShare.Builder(this).setType(“text/plain”)
.setText(“Google+ Demo http://cs2guru.com”)
.setContentUrl(Uri.parse(“http://cs2guru.com”)).getIntent();

startActivityForResult(shareIntent, 0);

}

/**
* API to handle sign out of user
*/
private void processSignOut() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
processUIUpdate(false);
}

}

/**
* API to handler sign in of user If error occurs while connecting process
* it in processSignInError() api
*/
private void processSignIn() {

if (!mGoogleApiClient.isConnecting()) {
processSignInError();
mSignInClicked = true;
}

}

/**
* API to process sign in error Handle error based on ConnectionResult
*/
private void processSignInError() {
if (mConnectionResult != null &amp;&amp; mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this,
SIGN_IN_REQUEST_CODE);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}

/**
* Callback for GoogleApiClient connection failure
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
ERROR_DIALOG_REQUEST_CODE).show();
return;
}
if (!mIntentInProgress) {
mConnectionResult = result;

if (mSignInClicked) {
processSignInError();
}
}

}

/**
* Callback for GoogleApiClient connection success
*/
@Override
public void onConnected(Bundle connectionHint) {
mSignInClicked = false;
Toast.makeText(getApplicationContext(), “Signed In Successfully”,
Toast.LENGTH_LONG).show();

processUserInfoAndUpdateUI();

processUIUpdate(true);

}

/**
* Callback for suspension of current connection
*/
@Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();

}

/**
* API to update signed in user information
*/
private void processUserInfoAndUpdateUI() {
Person signedInUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
if (signedInUser != null) {

if (signedInUser.hasDisplayName()) {
String userName = signedInUser.getDisplayName();
this.userName.setText(“Name: ” + userName);
}

if (signedInUser.hasTagline()) {
String tagLine = signedInUser.getTagline();
this.userTagLine.setText(“TagLine: ” + tagLine);
this.userTagLine.setVisibility(View.VISIBLE);
}

if (signedInUser.hasAboutMe()) {
String aboutMe = signedInUser.getAboutMe();
this.userAboutMe.setText(“About Me: ” + aboutMe);
this.userAboutMe.setVisibility(View.VISIBLE);
}

if (signedInUser.hasBirthday()) {
String birthday = signedInUser.getBirthday();
this.userBirthday.setText(“DOB ” + birthday);
this.userBirthday.setVisibility(View.VISIBLE);
}

if (signedInUser.hasCurrentLocation()) {
String userLocation = signedInUser.getCurrentLocation();
this.userLocation.setText(“Location: ” + userLocation);
this.userLocation.setVisibility(View.VISIBLE);
}

String userEmail = Plus.AccountApi.getAccountName(mGoogleApiClient);
this.userEmail.setText(“Email: ” + userEmail);

if (signedInUser.hasImage()) {
String userProfilePicUrl = signedInUser.getImage().getUrl();
// default size is 50×50 in pixels.changes it to desired size
int profilePicRequestSize = 250;

userProfilePicUrl = userProfilePicUrl.substring(0,
userProfilePicUrl.length() – 2) + profilePicRequestSize;
new UpdateProfilePicTask(userProfilePic)
.execute(userProfilePicUrl);
}

}
}

/**
* Background task to download user profile picture
*
* @author androidsrc.net
*
*/
private class UpdateProfilePicTask extends AsyncTask&lt;String, Void, Bitmap&gt; {

WeakReference profileView;

public UpdateProfilePicTask(ImageView img) {
profileView = new WeakReference(img);
}

@Override
protected Bitmap doInBackground(String… params) {
Bitmap profilePic = null;
try {
URL downloadURL = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) downloadURL
.openConnection();
int responseCode = conn.getResponseCode();
if (responseCode != 200)
throw new Exception(“Error in connection”);
InputStream is = conn.getInputStream();
profilePic = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return profilePic;
}

@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
if (result != null &amp;&amp; profileView != null) {
ImageView view = profileView.get();
if (view != null)
view.setImageBitmap(result);
}
}

}
}
[/java]

3.6 Build and Run your application

If you have followed all steps carefully, build and run your application. You will be able to sign in to your application using Google+ Sign In. You can quickly gather all public information about your application user and share posts from your application itself.

You may also like...

Leave a Reply

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