The Google plus Social API Integration

Google plus Social API Integration (G+ Login in android)

Before Social login in android, first of all, you have to enable your app. 

Step 1:   To enable your app to get Google plus user profile, open following after that click on Create a New Project.

Step 2: install/update Google Play Services-

 In Android Studio, 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 which use Google APIs require a google-services.json file 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)

Step 4: Go back following link click on Configure A Project.

Google plus Social API Integration (G+ Login in android)

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)

Download Your Credentials (Google-service.json) file. After that copy the Google-service.json file and paste it into your project.

Google plus Social API Integration (G+ Login in android)

Step 5: Create Your Project

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

allprojects {
    repositories {

Then, in your app-level build.gradle file, declare Google Play services as a dependency:

apply plugin: ''
    dependencies {
        compile ''

Step 6:   Add the Google Sign in button in Your Project (

 android:layout_height="wrap_content" />

Add the below code in your 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(;
public void onClick(View v) {
    switch (v.getId()) {
        // ...
public void googleSignIn() {
   Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
   startActivityForResult(signInIntent, REQ_CODE_GOOGLE_SIGN_IN);
public void startActivityForResult(Intent intent, int requestCode) {
    intent.putExtra("requestCode", requestCode);
    super.startActivityForResult(intent, requestCode);
public 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);
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;
public void ifSuccess(boolean check) {
    if (check) {
        try {
            String className = getIntent().getStringExtra("ClassName");
            if(className.equals("LoginRegisterFragment") || className.equals("UserActivity") || className.equals("RegisterActivity")) {
                Intent intent = new Intent(UserLoginActivity.this, UserActivity.class);
        } catch (Exception e) {
    } else {
        Toast.makeText(this, "email or password is incorrect", Toast.LENGTH_SHORT).show();

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;
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;
    public void onPreExecute() {
    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);
            } else {
                serviceUrl = new URL(ServiceProvider.SIGNIN_ENDPOINT_SOCIAL);
                postDataParams.put("EmailID", mEmail);
                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) {
        return null;
    public void onPostExecute(Boolean 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) {
        return false;

 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.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            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);
            Writer wr = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = "";
                while((line = in.readLine()) != null) {
                Log.v("JSON", sb.toString()); //JSON returned
            } 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...!!!

  Modified On Nov-20-2019 05:48:36 AM

Leave Comment