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 https://console.developers.google.com/cloud-resource-manager 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 https://developers.google.com/identity/sign-in/android/start-integrating 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 {
        google()
    }
}

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

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);
@Override
public 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);
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
    intent.putExtra("requestCode", requestCode);
    super.startActivityForResult(intent, requestCode);
}
@Override
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);
        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();
}
@Override
public 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...!!!

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

Leave Comment