Tuesday, April 29, 2014

Sign-in Google Plus Account in Android Example

Sign-in Google Plus Account in Android  Example

This post about how to signin Google plus via android application.
Step 1 - Create sample app
First Create the sample application

Step 2 - Add Google play service library project

Import googleplayservice library project  into eclipse work space




Then goto your sample project  right click ->properties - > android ->add the google play service library  to your project.


After the library it should show green indicator and apply it


Step 3 -Get SHA1 hash Value

For enabling Google + API  need SHA1 hash key.
Let see how to get sha1 hash key value .
We can get sha1 hash key value in many ways.

First One 

Goto window -> eclipse -> window -> select preference ->select android tab
and get the highlighted value is SHA1 hash values.





OR

Second way to get SHA1 hash  fingerprint value

Export the application with your keystore file

On the export window you can able see SHA1 hash value which have highlighted and Copy the SHA1 hash values


Step 4 -Enable Google+ Api 

For enable Google plus api go to Google API Console and Find the Google+ Api option and you can see the below screen .
1.     In the Google APIs Console Description: https://developers.google.com/+/mobile/images/OpenInNewWindow14x14.png, create an API project for your application.
2.     In the Services pane, enable the Google+ API and any other APIs that your app requires.







Step 5 -Create an OAuth 2.0 Client ID 
For Create an OAuth 2.0 Client ID the Credentials tab and create new client ID





Step 6- Consent Screen

Then goto  consent screen tab select email id and give product name save it



Step 7

Then come to your project
Create signin XML layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FFFFFF"
    android:padding="20dip">
    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dip"
        />

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="9pt"
        android:text="" />

    <ImageView
        android:id="@+id/profileImage"
        android:layout_width="200dp"
        android:layout_height="200dp"
        />

</LinearLayout>


Need to add following permission in manifest
  <!-- So that we can get the account name -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <!-- Used to request data from the Google+ APIs in the SignInActivity -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Required if we need to invalidate access tokens -->
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

Activity Code
In the activity code have all the method connect and disconnect and Callback method.

package com.vj.googleplussign;

import java.io.IOException;
import java.net.URI;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
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.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

public class MainActivity extends Activity implements ConnectionCallbacks,
              OnConnectionFailedListener {

       /* Request code used to invoke sign in user interactions. */
       private static final int RC_SIGN_IN = 0;

       /* Client used to interact with Google APIs. */
       private GoogleApiClient mGoogleApiClient;

       /*
        * A flag indicating that a PendingIntent is in progress and prevents us
        * from starting further intents.
        */

       private boolean mIntentInProgress;
       TextView textView;
       ImageView profileImage;
       com.google.android.gms.common.SignInButton signInBtn;

       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);

              StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                           .permitAll().build();
              StrictMode.setThreadPolicy(policy);

              setContentView(R.layout.activity_main);
              mGoogleApiClient = new GoogleApiClient.Builder(this)
                           .addConnectionCallbacks(this)
                           .addOnConnectionFailedListener(this).addApi(Plus.API, null)
                           .addScope(Plus.SCOPE_PLUS_LOGIN).build();

              textView = (TextView) findViewById(R.id.username);
              profileImage = (ImageView) findViewById(R.id.profileImage);
              signInBtn = (com.google.android.gms.common.SignInButton) findViewById(R.id.sign_in_button);
              signInBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View arg0) {
                           mGoogleApiClient.connect();

                     }
              });
       }

       protected void onStart() {
              super.onStart();

       }

       protected void onStop() {
              super.onStop();

              if (mGoogleApiClient.isConnected()) {
                     mGoogleApiClient.disconnect();
              }
       }

       @Override
       public void onConnectionFailed(ConnectionResult arg0) {

              if (!mIntentInProgress && arg0.hasResolution()) {
                     try {
                           mIntentInProgress = true;
                            arg0.startResolutionForResult(this, RC_SIGN_IN);
                     } catch (SendIntentException e) {
                           // The intent was canceled before it was sent. Return to the
                           // default
                           // state and attempt to connect to get an updated
                           // ConnectionResult.
                           mIntentInProgress = false;
                           mGoogleApiClient.connect();
                     }

              }

              // Log.e("error", "error code" + arg0.getResolution());
              Toast.makeText(this, "User is onConnectionFailed!", Toast.LENGTH_LONG)
                           .show();
       }

       @Override
       protected void onActivityResult(int requestCode, int responseCode,
                     Intent intent) {
              if (requestCode == RC_SIGN_IN) {
                     mIntentInProgress = false;
                     if (!mGoogleApiClient.isConnecting()) {
                           mGoogleApiClient.connect();
                     }
              }
       }

       @Override
       public void onConnected(Bundle arg0) {

              Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
              signInBtn.setVisibility(View.GONE);
              if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                     Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
                     textView.setText("Welcome : " + person.getDisplayName());
                     try {
                           JSONObject jsonObject = new JSONObject(person.getImage()
                                         .toString());
                           String imageUrl = jsonObject.getString("url");

                           try {
                                  URL url = new URL(imageUrl);
                                  Bitmap bmp;
                                  bmp = BitmapFactory.decodeStream(url.openConnection()
                                                .getInputStream());
                                  profileImage.setImageBitmap(bmp);
                           } catch (IOException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                            }

                     } catch (JSONException e) {
                           // TODO Auto-generated catch block
                           e.printStackTrace();
                     }

              }

       }

       @Override
       public void onConnectionSuspended(int arg0) {

              Toast.makeText(this, "User is onConnectionSuspended!",
                           Toast.LENGTH_LONG).show();
       }

}


Screen Shot






Download Source Code Here

No comments:

Post a Comment

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...