Friday, 23 October 2015

Google Plus Android login in Android Studio.


Now a days users installing android application does not want to fill the sign up forms.
It is easy and less time consuming by signing up by their social page login like Facebook  or Google plus.
This tutorial helps in integrating google plus login in your Android application.
By Integrating Google Plus, you can get the user details from user google account.

Follow the below steps for Google play integration using Android Studio.

Step 1: Download Google Play service using Android SDK manager.





































Step 2: Enable Google Plus Login
          2.1: Get SHA-1 Fingerprint

Java keytool can be used to generate SHA-1 fingerprint. Open your Command Prompt and execute the following command to generate SHA-1 fingerprint.
On windows 
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

On Linux or Mac OS:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Use the command to generate SHA-1 Fingerprint



       2.2 : Creating your project in  Google Developers Console.
Open Google APIs console
 Create a project from selecting the drop down menu select a Project.

Click on the project name to go in to APIs and Auth page

2.3 : On the left, under APIs & auth section, click on APIs and on the right enable Google+ API service.


2.4 :  Now Enable the API.

2.5: Now Click on credential -> Add Credentials -> OAuth 2.0 client id


2.6:  In current Page select Android from Create Client ID.
Fill the package name of your project,  SHA1 finger print, enable the Deep Linking option to activate interactive posts and all the other parameters to create 

OAuth 2.0 client IDs as shown in the image below .



Now you are done with Google developer console.

Step 3: Edit your Android Project to login google plus.

3.1 : Include com.google.android.gms:play-services:7.5.0 in build.gradle 
file of your project.

dependencies {
    
    compile 'com.google.android.gms:play-services:8.1.0'
}

3.2 : Change your Manifesto.xml file accordingly.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.test.googlepluslogin" >
    <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="@mipmap/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>

"android.permission.GET_ACCOUNTS" permission is used To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user.





Code for the MainActivity.java

package com.test.googlepluslogin;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
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.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
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 AppCompatActivity implements OnClickListener,
        GoogleApiClient.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;

    private boolean mShouldResolve;

    /*finding connection result*/    private ConnectionResult connectionResult;

    private SignInButton googleSignInButton;
    private Button googleSignOutButton;
    private TextView loggedInUsrName, loggedInUsrMail, usrNotSignedIn;
    private LinearLayout viewContainer;

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

        googleSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
        googleSignOutButton = (Button) findViewById(R.id.sign_out_button);
        loggedInUsrName = (TextView) findViewById(R.id.loggedInUsrName);
        loggedInUsrMail = (TextView) findViewById(R.id.loggedInUsrMail);
        usrNotSignedIn = (TextView) findViewById(R.id.notSignedIn_tv);
        viewContainer = (LinearLayout) findViewById(R.id.text_view_container);


      /*  Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolBar);*/
        googleSignInButton.setOnClickListener(this);
        googleSignOutButton.setOnClickListener(this);

        //Builg GoogleApiClient        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN)
                .build();

    }

    protected void onStart() {
        super.onStart();
        //connect GoogleApiClient        mGoogleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        //disconnect GoogleApiClient        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    /*    Used for resolving errors during signIn    */    private void resolveSignInError() {
        if (connectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                connectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }

  

    /*    onConnectionFailed() was started with startIntentSenderForResult and the code RC_SIGN_IN,    we can capture the result inside Activity.onActivityResult.     */    @Override    protected void onActivityResult(int requestCode, int responseCode,
                                    Intent intent) {
        if (requestCode == RC_SIGN_IN) {
            if (responseCode != RESULT_OK) {
                mShouldResolve = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
    }
    /*  When the GoogleApiClient object is unable to establish a connection onConnectionFailed() is called   */    @Override    public void onConnectionFailed(ConnectionResult result) {
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                    0).show();
            return;
        }

        if (!mIntentInProgress) {

            connectionResult = result;

            if (mShouldResolve) {

                resolveSignInError();
            }
        }

    }
    

    /*    on the successfull connection onConnected is called     */    @Override    public void onConnected(Bundle arg0) {
        mShouldResolve = false;
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person person = Plus.PeopleApi                        .getCurrentPerson(mGoogleApiClient);
                String personName = person.getDisplayName();
                String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

                loggedInUsrName.setText(personName);
                loggedInUsrMail.setText(email);

                Toast.makeText(getApplicationContext(),
                        "You are Logged In " + personName, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "Couldnt Get the Person Info", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        signOutUI();

    }

    /*    sign out UI     */    private void signOutUI() {
        googleSignInButton.setVisibility(View.GONE);
        usrNotSignedIn.setVisibility(View.GONE);
        googleSignOutButton.setVisibility(View.VISIBLE);
        viewContainer.setVisibility(View.VISIBLE);
    }

    /*    SignIn UI     */    private void signInUI() {
        googleSignInButton.setVisibility(View.VISIBLE);
        usrNotSignedIn.setVisibility(View.VISIBLE);
        googleSignOutButton.setVisibility(View.GONE);
        viewContainer.setVisibility(View.GONE);
    }


    /*    called when the connection is suspended     */    @Override    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
        signInUI();
    }

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


    @Override    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                onSignInClicked();
                break;
            case R.id.sign_out_button:
                onSignOutClicked();
                break;
        }
    }

    /*    called when signIn Button is clicked     */    private void onSignInClicked() {
        if (!mGoogleApiClient.isConnecting()) {
            mShouldResolve = true;
            resolveSignInError();
        }
    }

    /*    called when sign out button is clicked     */    private void onSignOutClicked() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            signInUI();
        }
    }

}


Code for Activity_main

<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=".MainActivity">


    <LinearLayout        android:id="@+id/text_view_layout"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="vertical"        android:paddingLeft="16dp"        android:paddingRight="16dp"        android:visibility="gone"        android:weightSum="3"        android:layout_marginTop="100dp"        android:layout_marginBottom="20dp">

        <TextView            android:id="@+id/loggedInUsrName"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:padding="5dp"            android:textSize="25dp" />

        <TextView            android:id="@+id/loggedInUsrMail"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:padding="5dp"            android:textSize="25dp" />

    </LinearLayout>

    <Button        android:id="@+id/sign_out_button"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginBottom="10dp"        android:background="@android:color/holo_red_light"        android:layout_marginLeft="25dp"        android:layout_marginRight="25dp"        android:textColor="#fff"        android:textStyle="bold"        android:visibility="gone"        android:text="LOGOUT"/>

    <TextView        android:id="@+id/notSignedIn_tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:layout_marginTop="100dp"        android:layout_marginBottom="30dp"        android:textSize="25sp"        android:text="You are not Signed In"/>

    <com.google.android.gms.common.SignInButton        android:id="@+id/sign_in_button"        android:layout_width="250dp"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal" />

</LinearLayout>

After Executing the code in device you will gwt following screen.

After Sign in you will be moved to succefull signin page as below.

No comments:

Post a Comment