Skip to content

Coderzpassion.com

  • Sample Page

Android latest Google Plus Login Api Tutorial – Coderz Passion

August 8, 2022 by rohit

  • Detailed Tutorials

    • LinearLayout Concepts in Detail
    • Material Design Concepts
    • What you can do With RelativeLayout
    • SQLITE Database Concepts in Detail
    • Understanding Animations in Android
    • Understanding Service Concepts
    • Understanding Fragments in Android
    • Handler Concept in Detail
    • Android Working With Date
    • Working with Recycler View





  • Android latest Google Plus Login Api Tutorial

    March 18, 2016July 5, 2017

    In this Post, I will explain you step by step to integrate Google Plus Login in your Application.

    So, Let’s Start: –

    To use Google Plus I will need the following: –

    1. Create the key by enabling google plus API and get a configuration file.
    2. add a dependency in the android studio or add google play services as a library in Eclipse.
    3. Add permissions in AndroidManifest.xml and you are done.

    Let’s Create a key and get configuration file

    1.Create a Project at Google Developers Console.

    workingwithgoogleplacesapi

    Now Click on Enable and Manage API

    howtousegooglepluslogin

    Now Click on Google Plus API

    androidworkingwithgoogleplusapi

    Click on Enable API

    enablegoogleplusapi

    Now on the left click on Credentials=>Add Credentials=>API key

    gettingapikeyforgoogleplus

    Click on API key=>Android Key

    gettingandroidkey

    Set you API key name and add your package name and sha1 key

    addpackagename

    click on OAuth Consent Screen and add product name.it must be set before creating Client Id

    settingproductid

    Click on Add Credentials and  then select OAuth 2.0 Client Id

    createclientidforgoogleplusintegration

    Choose Android and set application package name and SHA1 key

    To generate SHA1 key type following command in your System Command Prompt

    On MAC/Linux

    keytool -exportcert -alias androiddebugkey -keystore "keystorepath" -list -v

    On Windows

    keytool -list -v -keystore "keystore path" -alias androiddebugkey -storepass android -keypass android
    

    clientidforgoogleplus

    Finally, I had got both API and Client Id and it looks like this

    home

    Now Generate a Configuration File and add it in your App directory.Visit google services page and generate configuration file.

    Add Project name created in developers console and Package name and click on Choose and configure services like this

    adding services

    Choose Google Sign In and add SHA Fingerprint and then click on Enable Google Sign In

    finally

    Then Finally, download JSON file and place it in your App Main Directory.

    Add the dependency to your project level Gradle  to automatically parse json file

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

    Then add dependency to your build.gradle to use Google Plus API in your Application

    compile 'com.google.android.gms:play-services-auth:8.3.0'

    Now add following permissions and meta tag in AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.GET_ACCOUNTS" />
        <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    
    
    <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />

    So, AndroidManifest.xml will look like this

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.coderzpassion.googlepsample">
        <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: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>
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />
        </application>
    
    </manifest>
    

    Now add google Sign-In Button to your activity_main.xml

    <?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.coderzpassion.googlepsample.MainActivity"
        tools:showIn="@layout/activity_main">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
    
        <com.google.android.gms.common.SignInButton
            android:id="@+id/sign_in_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </RelativeLayout>
    

    Now Implement OnConnectionFailedListener and ConnectionCallbacks to your MainActivity.java

    public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks

    Initialise GoogleSignInOptions and GoogleApiClient

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestProfile()
                    .requestScopes(new Scope(Scopes.PLUS_ME))
                    .requestScopes(new Scope(Scopes.PLUS_LOGIN))
                    .build();
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .enableAutoManage(this, this /* OnConnectionFailedListener */)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .build();

    Setting size of Google Sign In Button and setting click Listener

    SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
           signInButton.setSize(SignInButton.SIZE_STANDARD);
           signInButton.setScopes(gso.getScopeArray());
           signInButton.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
    //start intent for sign in result
                   Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                   startActivityForResult(signInIntent, RC_SIGN_IN);
               }
           });

    Implementing Interface Methods which are necessary like this

    @Override
       protected void onStart() {
           super.onStart();
           //add this to connect Google Client
           mGoogleApiClient.connect();
       }
    
       @Override
       protected void onStop() {
           super.onStop();
           //Stop the Google Client when activity is stopped
           if(mGoogleApiClient.isConnected())
           {
               mGoogleApiClient.disconnect();
           }
       }
    
       @Override
       protected void onResume() {
           super.onResume();
           if(mGoogleApiClient.isConnected())
           {
               mGoogleApiClient.connect();
           }
       }
    
       @Override
       public void onConnectionSuspended(int i) {
           mGoogleApiClient.connect();
       }
    
       @Override
       public void onConnectionFailed(ConnectionResult connectionResult) {
              if(!connectionResult.hasResolution())
              {
                  apiAvailability.getErrorDialog(MainActivity.this,connectionResult.getErrorCode(),requestcode).show();
              }
       }

    In onActivityResult check the request and get the result

     @Override
        protected 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) {
                requestcode=requestCode;
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                handleSignInResult(result);
            }
    else
    {
    //failed to connect
    }
    
        }

    getting user details from 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();
               String name=   acct.getDisplayName();
               String email=acct.getEmail();
               String id= acct.getIdToken();
    
           } else {
               // Signed out, show unauthenticated UI.
    
           }
       }

    To Sign Out the User

    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // ...
                    }
                });
    }

    So, Final Code will be

    package com.coderzpassion.googlepsample;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    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.GoogleApiAvailability;
    import com.google.android.gms.common.Scopes;
    import com.google.android.gms.common.SignInButton;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.Scope;
    
    public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks{
        int RC_SIGN_IN=1000;
        GoogleApiClient mGoogleApiClient;
        GoogleApiAvailability apiAvailability;
        int requestcode;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestProfile()
                    .requestScopes(new Scope(Scopes.PLUS_ME))
                    .requestScopes(new Scope(Scopes.PLUS_LOGIN))
                    .build();
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .enableAutoManage(this, this /* OnConnectionFailedListener */)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .build();
            setContentView(R.layout.activity_main);
    
    
    
            SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
            signInButton.setSize(SignInButton.SIZE_STANDARD);
            signInButton.setScopes(gso.getScopeArray());
            signInButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                    startActivityForResult(signInIntent, RC_SIGN_IN);
                }
            });
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            //add this to connect Google Client
            mGoogleApiClient.connect();
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            //Stop the Google Client when activity is stopped
            if(mGoogleApiClient.isConnected())
            {
                mGoogleApiClient.disconnect();
            }
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            if(mGoogleApiClient.isConnected())
            {
                mGoogleApiClient.connect();
            }
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            mGoogleApiClient.connect();
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
               if(!connectionResult.hasResolution())
               {
                   apiAvailability.getErrorDialog(MainActivity.this,connectionResult.getErrorCode(),requestcode).show();
               }
        }
    
        @Override
        public void onConnected(Bundle bundle) {
    
        }
    
        @Override
        protected 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) {
                requestcode=requestCode;
                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();
                String name=   acct.getDisplayName();
                String email=acct.getEmail();
                String id= acct.getIdToken();
    
            } else {
                // Signed out, show unauthenticated UI.
    
            }
        }
        @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 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();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    }
    

     

     

     

     

     

     

    Share this:

    • Click to share on Twitter (Opens in new window)
    • Click to share on Facebook (Opens in new window)
    • Click to share on Google+ (Opens in new window)

    Like this:

    Like Loading…

    Related

    Posted in: Uncategorized | Tagged: GooglePlus Sign In


    Post navigation

     Android Facebook Login in Application using latest Facebook SDK Tutorial
    How to show/display Alert Dialog/Dialog in Android.