---
title: "The Google plus Social API Integration"  
description: "Before Social login in android, first of all, you have to enable your app."  
author: "Arti Mishra"  
published: 2018-09-21  
updated: 2019-11-20  
canonical: https://www.mindstick.com/articles/13142/the-google-plus-social-api-integration  
category: "android apps"  
tags: ["android"]  
reading_time: 10 minutes  

---

# The Google plus Social API Integration

## Google plus Social API Integration (G+ Login in android)

Before [Social login](https://www.mindstick.com/articles/12423/social-login-magento-2-one-click-to-register-social) in android, first of all, you have to **enable [your app](https://answers.mindstick.com/qa/33368/how-will-you-design-a-listview-which-downloads-a-lot-of-images-and-displays-in-it-without-getting-your-app-hanged-whats-the-best-possible-way).** \

**Step 1:** To enable your app to get Google plus [user profile](https://answers.mindstick.com/qa/93400/how-can-i-achieve-a-verified-user-profile-at-mindstick), open following **https://console.developers.google.com/cloud-resource-manager** after that click on **Create** a **New Project.**

**Step 2:** install/update Google Play [Services](https://answers.mindstick.com/qa/93329/what-is-a-pest-control-services)-

In [Android Studio](https://answers.mindstick.com/qa/51181/how-to-create-a-log-error-file-in-android-studio-and-also-perform-read-write-operation-in-a-file), select **Tools > Android > SDK Manager>SDK Tools** and install or update the play services.

**Step 3:** Generating **Google-Service.json** File.

Now all the android [projects](https://www.mindstick.com/articles/105927/how-to-excel-at-managing-multiple-projects) which use **Google APIs require a google-services.[json file](https://www.mindstick.com/forum/158972/how-to-read-appsettings-values-from-a-json-file-in-asp-dot-net-core)** to be placed in the project’s app folder. Follow the below steps to get your google-services.json file.

--> First of all, generate the SHA-1 fingerprint. Java key-tool can be used to generate the SHA-1 fingerprint. Open your terminal(cmd) and execute the following command to generate the SHA-1 fingerprint. If it asks for a password, type android, and press enter.

## For windows follow the following command in java bin folder-

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

## In My Project

First we open cmd --->cd C:\Program Files\Java\jdk-9.0.4\bin--->press enter --->after that write below command to generate SHA-1 fingerprints.

**keytool -list -v -keystore "C:\Users\msclient009\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android**

![Google plus Social API Integration (G+ Login in android)](https://www.mindstick.com/mindstickarticle/4c8ad5fb-a61f-4e0d-a372-e62706945dcd/images/643c4949-344b-4c23-b501-80921fb92be1.png)\

**Step 4:** Go back following link **https://developers.google.com/identity/sign-in/android/start-integrating** click on **Configure A Project.**

![Google plus Social API Integration (G+ Login in android)](https://www.mindstick.com/mindstickarticle/4c8ad5fb-a61f-4e0d-a372-e62706945dcd/images/96720134-1021-40bd-9f21-885cca92af97.png) **\**

After that **Select or Create Project** click on next select your **platform Android** and **fill the required field** and click on create.

![Google plus Social API Integration (G+ Login in android)](https://www.mindstick.com/mindstickarticle/4c8ad5fb-a61f-4e0d-a372-e62706945dcd/images/c554aa83-5926-4df8-be05-0a7742677d3d.png)\

[Download](https://www.mindstick.com/blog/114673/download-hungry-shark-evolution-mod-apk-unlimited-money) Your **Credentials (Google-service.json)** file. After that **copy the Google-service.json file and paste it into [your project](https://answers.mindstick.com/qa/93843/is-it-necessary-to-add-bootstrap-js-and-bootstrap-css-both-in-your-project).**

![Google plus Social API Integration (G+ Login in android)](https://www.mindstick.com/mindstickarticle/4c8ad5fb-a61f-4e0d-a372-e62706945dcd/images/dd19ec2b-0b16-4121-b952-616ec3354175.png)\

## \

## Step 5: Create Your Project

In your project's top-level **build.gradle** file adds the below code.

```
allprojects {    repositories {        google()    }}
```

Then, in your app-level **build.gradle** file, declare Google Play services as a [dependency](https://www.mindstick.com/news/2358/apple-will-use-us-made-semiconductors-in-its-products-to-lessen-its-dependency-on-asia):

```
apply plugin: 'com.android.application'    ...    dependencies {        compile 'com.google.android.gms:play-services-auth:15.0.1'    }
```

**Step 6:** Add the Google Sign in button in Your Project (**main_activity.java**).

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

**Add the below code in your MainActivity.java file.**

```
mSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();mGoogleApiClient = new GoogleApiClient.Builder(this)        .enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, mSignInOptions).build();Button signInButton = findViewById(R.id.sign_in_button);signInButton.setOnClickListener(this);@Overridepublic void onClick(View v) {    switch (v.getId()) {        case R.id.sign_in_button:            signIn();            break;        // ...    }}public void googleSignIn() {   Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);   startActivityForResult(signInIntent, REQ_CODE_GOOGLE_SIGN_IN);}@Overridepublic void startActivityForResult(Intent intent, int requestCode) {    intent.putExtra("requestCode", requestCode);    super.startActivityForResult(intent, requestCode);}@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {    super.onActivityResult(requestCode, resultCode, data);    Log.v("Request Code", String.valueOf(requestCode));    if (requestCode == REQ_CODE_GOOGLE_SIGN_IN) {        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);        handleSignInResult(task);    }}private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {     try {        GoogleSignInAccount account = completedTask.getResult(ApiException.class);         String name = account.getDisplayName();         String firstName = "";         String lastName = "";         if (name != null) {             int end = name.lastIndexOf(' ');             if (end >= 0) {                 firstName = name.substring(0, end);                 lastName = name.substring(end + 1, name.length());             }         }         Log.v(" Google Profile Name : ", firstName + lastName + account.getEmail() + account.getId());         Toast.makeText(getApplicationContext(),"Google+ Login Successful",Toast.LENGTH_SHORT).show();         loginApi("Google", account.getId(), firstName, lastName, account.getEmail());     } catch (ApiException e) {         Log.e("Google Plus Login : ", e.getMessage(), e);         Log.w("Value", "signInResult:failed code=" + e.getStatusCode());         Toast.makeText(this,"Login failure : "+ e.getStatusCode(), Toast.LENGTH_LONG).show();     } }public void loginApi(String provider, String providerId, String firstName, String lastName, String emailId) {    LoginAsyncTask asyncTask = new LoginAsyncTask(getApplicationContext(), provider, providerId, firstName, lastName, emailId);    asyncTask.delegate = this;    asyncTask.execute();}@Overridepublic void ifSuccess(boolean check) {    if (check) {        loginProgress.setVisibility(View.GONE);        try {            String className = getIntent().getStringExtra("ClassName");            if(className.equals("LoginRegisterFragment") || className.equals("UserActivity") || className.equals("RegisterActivity")) {                Intent intent = new Intent(UserLoginActivity.this, UserActivity.class);                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);                startActivity(intent);                finish();            }        } catch (Exception e) {            e.printStackTrace();        }        previousPage();        finish();    } else {        loginProgress.setVisibility(View.GONE);        loginSubmit.setClickable(true);        Toast.makeText(this, "email or password is incorrect", Toast.LENGTH_SHORT).show();    }}
```

**LoginAsyncTask.java**\

```
package com.example.msclient010.mindstickqna.AsyncTask;import android.content.Context;import android.os.AsyncTask;import android.util.Log;import com.example.msclient010.mindstickqna.Interface.LoginCheck;import com.example.msclient010.mindstickqna.Utils.SaveSharedPreference;import com.example.msclient010.mindstickqna.Utils.ServiceProvider;import org.json.JSONException;import org.json.JSONObject;import java.net.URL;public class LoginAsyncTask extends AsyncTask<Void, Boolean, Boolean> {    private String mEmail, mPassword;   // private final String LOG_TAG = LoginAsyncTask.class.getSimpleName();    private Context mContext;    String provider, providerId, firstName, lastName;    public LoginCheck delegate = null;    public LoginAsyncTask(Context context, String email, String pass) {        mContext = context;        mEmail = email;        mPassword = pass;    }    public LoginAsyncTask(Context mContext, String provider, String providerId, String firstName, String lastName, String emailId) {        this.mContext = mContext;        this.provider = provider;        this.providerId = providerId;        this.firstName = firstName;        this.lastName = lastName;        this.mEmail = emailId;    }    @Override    public void onPreExecute() {    }    @Override    protected Boolean doInBackground(Void... strings) {        JSONObject postDataParams = new JSONObject();        try {            URL serviceUrl;            String postData;            if (provider == null) {                serviceUrl = new URL(ServiceProvider.SIGNIN_ENDPOINT);                postDataParams.put("EmailID", mEmail);                postDataParams.put("Password",mPassword);            } else {                serviceUrl = new URL(ServiceProvider.SIGNIN_ENDPOINT_SOCIAL);                postDataParams.put("EmailID", mEmail);                postDataParams.put("Password",mPassword);                postDataParams.put("FirstName", firstName);                postDataParams.put("LastName", lastName);                postDataParams.put("Provider", provider);                postDataParams.put("ProviderId", providerId);            }            return parseJson(ServiceProvider.postMethod(postDataParams, serviceUrl));        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    @Override    public void onPostExecute(Boolean result) {        delegate.ifSuccess(result);        delegate.updatedContent(result, false);    }  public boolean parseJson(String response) {        final Boolean success;        JSONObject recentData = null;        Log.v("Response", response);        try {            recentData = new JSONObject(response);            success = recentData.getBoolean("IsSuccess");            if (success) {                String fname = null, lname = null;                long userId = 0;                JSONObject arrayResult = recentData.getJSONObject("Data");                fname = arrayResult.getString("FirstName");                lname = arrayResult.getString("LastName");                userId = arrayResult.getLong("ID");                Log.v("DATA", fname + lname + userId);                SaveSharedPreference.setFirstName(mContext, fname);                SaveSharedPreference.setLastName(mContext, lname);                SaveSharedPreference.setUserId(mContext, String.valueOf(userId));                SaveSharedPreference.setEmailId(mContext, mEmail);                SaveSharedPreference.setPassword(mContext, mPassword);                return true;            }        } catch (JSONException e) {            e.printStackTrace();        }        return false;    }}
```

**ServiceProvider.java**\

```
 public static String postMethod(JSONObject postDataParams, URL url){
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        StringBuffer sb = new StringBuffer("");
        try {
            Log.e("params", postDataParams.toString().replace("\\",""));
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setReadTimeout(800000);
            urlConnection.setConnectTimeout(800000);
            long unixTime = System.currentTimeMillis() / 1000L;
            String nonce = DataProvider.GenerateGUID();
            String postData = postDataParams.toString();
            Log.v("Login Data", postData);
            String encryptedPostData = Base64Provider.encode(DataProvider.aesEncrypt(postData.getBytes("UTF-8"), ServiceProvider.KEY_ENCRYPTION.getBytes("UTF-8")));
            String signatureRaw = ServiceProvider.APP_ID + "POST" + ServiceProvider.URLEncode(url.toString()) + String.valueOf(unixTime) + nonce + encryptedPostData;
            String signature = DataProvider.hmacEncrypt(ServiceProvider.API_KEY, signatureRaw);
            String headerValue = "amx " + ServiceProvider.APP_ID + ":" + signature + ":" + nonce + ":" + String.valueOf(unixTime);
            urlConnection.setRequestProperty("Authorization", headerValue);
            urlConnection.setDoOutput(true);
            Writer wr = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            wr.write(postData);
            wr.flush();
            wr.close();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = "";
                while((line = in.readLine()) != null) {
                    sb.append(line);
                    break;
                }
                Log.v("JSON", sb.toString());  //JSON returned
               in.close();
            } else {
                Log.v("Some error", "in login" + String.valueOf(responseCode));
            }
        } catch (Exception e) {e.printStackTrace();
        }
       return sb.toString();
    }
```

## "I hope this will help you". Thanks...!!!

---

Original Source: https://www.mindstick.com/articles/13142/the-google-plus-social-api-integration

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
