Question Detail

How to Start Integrating Google Sign-In into Android App. Google Sign-In manages the OAuth 2.0 flow and token lifecycle, simplifying  integration with Google APIs.
How can i integrating GooglePlus Login api with my android App?Image result for integrate Google Plus Login


Thread Reply

Anonymous

- 1 years ago

Generating Google-Services.json

Google apis, requires google-services.json file to be placed in project’s app folder. Follow the below steps for google-services.json file.

Java keytool can be used to generate SHA-1 fingerprint. Open your terminal and execute the following command to generate SHA-1 fingerprint. If it ask for password, type android and press enter.

If cmd raise error 'keytool' is not recognized as an internal or external command,
operable program or batch file.

set a path to your C:\Program Files\Java\jdk1.8.0_131\bin

On windows

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

In the output you can notice SHA1 fingerprint.Image result for SHA1 fingerprint

click on Get A Configuration File button. This will redirect you to a page where you can choose the project and package name.

1. Clear first step APP name and Package 

2. Paste the SHA-1 fingerprint and click on Enable Google Sign-In. Finally, click on Generate Configuration File to download your google-services.json


Open Your android Project in android Studio


 
  1.   project level build.gradle and add ‘com.google.gms:google-services:3.0.0’ class path to dependencies.

    dependencies {

            classpath 'com.android.tools.build:gradle:2.3.3'

            classpath 'com.google.gms:google-services:3.0.0'

        }

  2. app level build.gradle and add ‘compile com.google.android.gms:play-services-auth:9.2.1’ to dependencies. At the bottom of the file, add apply plugin: ‘com.google.gms.google-services’

    dependencies {

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

    }

    apply plugin: 'com.google.gms.google-services'

    Now I am designing a simple layout to display user’s profile picture, name, email and other buttons. Paste the below code in layout file of your main activity. In my case my layout file name is activity_main.xml

    activity_main.xml

    <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">

     

        <com.google.android.gms.common.SignInButton

            android:id="@+id/btn_sign_in"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_marginBottom="20dp"/>

     

        <Button

            android:id="@+id/btn_sign_out"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="@string/btn_logout_from_google"

            android:visibility="gone"

            android:layout_marginBottom="10dp"/>

     

        <Button

            android:id="@+id/btn_revoke_access"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="@string/btn_revoke_access"

            android:visibility="gone" />

     

    </LinearLayout>

  3. Now open MainActivity.java and do the below modifications. The code is self explanatory and very easy understand.
  4. > implement the activity from GoogleApiClient.OnConnectionFailedListener

    > Create the GoogleApiClient instance in onCrate() method.

    > signIn() performs google plus sign in, signOut() logs out user from google account and revokeAccess()completely revokes the access from google plus.

    > onActivityResult() is called whenever user returns from Google Login UI.

    > In onStart() method, checked for cached google sign in session and appropriate UI is displayed.

    > handleSignInResult() handles the google plus profile information upon successful login.

    > updateUI() toggles the UI by showing / hiding the appropriate buttons and text views.

    •  

      import android.app.ProgressDialog;

      import android.content.Intent;

      import android.os.Bundle;

      import android.support.annotation.NonNull;

      import android.support.v7.app.AppCompatActivity;

      import android.util.Log;

      import android.view.View;

      import android.widget.Button;

      import android.widget.LinearLayout;

      import android.widget.TextView;

      import com.bumptech.glide.load.engine.DiskCacheStrategy;

      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.SignInButton;

      import com.google.android.gms.common.api.GoogleApiClient;

      import com.google.android.gms.common.api.OptionalPendingResult;

      import com.google.android.gms.common.api.ResultCallback;

      import com.google.android.gms.common.api.Status;

      public class MainActivity extends AppCompatActivity implements View.OnClickListener,

              GoogleApiClient.OnConnectionFailedListener {

          private static final String TAG = MainActivity.class.getSimpleName();

          private static final int RC_SIGN_IN = 007;

          private GoogleApiClient mGoogleApiClient;

          private ProgressDialog mProgressDialog;

          private SignInButton btnSignIn;

          private Button btnSignOut, btnRevokeAccess;

          private LinearLayout llProfileLayout;

          @Override

          protected void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.activity_main);

              btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);

              btnSignOut = (Button) findViewById(R.id.btn_sign_out);

              btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);

              llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);

              btnSignIn.setOnClickListener(this);

              btnSignOut.setOnClickListener(this);

              btnRevokeAccess.setOnClickListener(this);

              GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();

              mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();

              // Customizing G+ button

              btnSignIn.setSize(SignInButton.SIZE_STANDARD);

              btnSignIn.setScopes(gso.getScopeArray());

          }

          private void signIn() {

              Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);

              startActivityForResult(signInIntent, RC_SIGN_IN);

          }

          private void signOut() {

              Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(

                      new ResultCallback<Status>() {

                          @Override

                          public void onResult(Status status) {

                              updateUI(false);

                          }

                      });

          }

           private void handleSignInResult(GoogleSignInResult result) {

              Log.d(TAG, "handleSignInResult:" + result.isSuccess());

              if (result.isSuccess()) {

                  // Signed in successfully, show authenticated UI.

                  GoogleSignInAccount acct = result.getSignInAccount();

       

                  Log.e(TAG, "display name: " + acct.getDisplayName());

       

                  String personName = acct.getDisplayName();

                  String personPhotoUrl = acct.getPhotoUrl().toString();

                  String email = acct.getEmail();

       

                  Log.e(TAG, "Name: " + personName + ", email: " + email

                          + ", Image: " + personPhotoUrl);

      Toast.makeText(this,"Name: " + personName + ", email: " + email+ ", Image: " + personPhotoUrl,Toast.LENGTH_LONG).show();

                  updateUI(true);

              } else {

                  // Signed out, show unauthenticated UI.

                  updateUI(false);

              }

          }

          @Override

          public void onClick(View v) {

              int id = v.getId();

       

              switch (id) {

                  case R.id.btn_sign_in:

                      signIn();

                      break;

       

                  case R.id.btn_sign_out:

                      signOut();

                      break;

                 }

          }

       

          @Override

          public 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) {

                  GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

                  handleSignInResult(result);

              }

          }

          @Override

          public void onStart() {

              super.onStart();

       

              OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);

              if (opr.isDone()) {

                  // If the user's cached credentials are valid, the OptionalPendingResult will be "done"

                  // and the GoogleSignInResult will be available instantly.

                  Log.d(TAG, "Got cached sign-in");

                  GoogleSignInResult result = opr.get();

                  handleSignInResult(result);

              } else {

                  // If the user has not previously signed in on this device or the sign-in has expired,

                  // this asynchronous branch will attempt to sign in the user silently.  Cross-device

                  // single sign-on will occur in this branch.

                  showProgressDialog();

                  opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {

                      @Override

                      public void onResult(GoogleSignInResult googleSignInResult) {

                          hideProgressDialog();

                          handleSignInResult(googleSignInResult);

                      }

                  });

              }

          }

          @Override

          public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

              // An unresolvable error has occurred and Google APIs (including Sign-In) will not

              // be available.

              Log.d(TAG, "onConnectionFailed:" + connectionResult);

          }

          private void showProgressDialog() {

              if (mProgressDialog == null) {

                  mProgressDialog = new ProgressDialog(this);

                  mProgressDialog.setMessage(getString(R.string.loading));

                  mProgressDialog.setIndeterminate(true);

              }

              mProgressDialog.show();

          }

          private void hideProgressDialog() {

              if (mProgressDialog != null && mProgressDialog.isShowing()) {

                  mProgressDialog.hide();

              }

          }

          private void updateUI(boolean isSignedIn) {

              if (isSignedIn) {

                  btnSignIn.setVisibility(View.GONE);

                  btnSignOut.setVisibility(View.VISIBLE);

                  llProfileLayout.setVisibility(View.VISIBLE);

              } else {

                  btnSignIn.setVisibility(View.VISIBLE);

                  btnSignOut.setVisibility(View.GONE);         

                  llProfileLayout.setVisibility(View.GONE);

              }

          }

      }

alex levine

- 2 months ago

In the Latest Version of Android Studio, many things got very easy by its own Like using Firebase easy way to Integrate Google you have to follow just a few steps and some code have to copy paste in your login Activity your Google Login Integration has been complete very easily.

To Integrate Google Sign-In to Android app you have to create a New Android Project or if you already created your project go to Menu Bar of Android Studio Select Tools 

Google Login Android Studio Tools > Firebase

 

It will open Assistant at the left side which has many firebase options we are Integrating Google Login with firebase so we will choose Authentication in the Assistant Tab 

Google Login in android tutorial Firebase > Authentication

You have to click on Email and Password authentication it will expand with options 

  1. Connect your app to Firebase > Connect to Firebase it open a dialog box choose existing or create a new project on firebase from Android Studio.
  2. Add Firebase Authentication to your App > when Connect with Firebase just click on it and sync your project it will Add required dependencies automatically.

Just sync your Project now and go to Firebase Console and find your application name in the grid open App.

Enable Google Login permission in firebase

Select Authentication left the menu and go to Sign-in method Google enable Switch button and save everything as it is come back in your Android Studio project and Start coding part now.

 

activity_login.XML

<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center"
    android:background="#eee"
    android:orientation="vertical"
    tools:context=".LoginActivity">

    <LinearLayout
        android:id="@+id/after_loginData_ID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center">

        <TextView
            android:id="@+id/google_userDetails_ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:text="Google User Name: Hemant Sharma" />

        <Button
            android:id="@+id/logout_Button_ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="#fff"
            android:textColor="#d23939"
            android:padding="8dp"
            android:drawableLeft="@drawable/googleg_standard_color_18"
            android:drawablePadding="5dp"
            android:text="Sign out from Google" />
    </LinearLayout>

    <Button
        android:id="@+id/login_Button_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#fff"
        android:textColor="#d23939"
        android:padding="8dp"
        android:drawableLeft="@drawable/googleg_standard_color_18"
        android:drawablePadding="5dp"
        android:text="Sign In with Google" />

</LinearLayout>

AndroidMainfest.xml

set some permission to ignore some unwanted App crashes

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />

 

LoginActivity.java

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;

import static android.content.ContentValues.TAG;

public class LoginActivity extends AppCompatActivity {
    Activity mActivity;
    LinearLayout after_loginData;
    Button login_Button, logout_Button;
    FirebaseAuth firebaseAuth;
    TextView google_userDetails;
    ProgressDialog dialog;
    GoogleSignInOptions gso;
    int googleLoginCode = 458;
    FirebaseAuth.AuthStateListener authStateListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        this.mActivity = LoginActivity.this;
        firebaseAuth = FirebaseAuth.getInstance();
        after_loginData = findViewById(R.id.after_loginData_ID);
        google_userDetails = findViewById(R.id.google_userDetails_ID);
        after_loginData.setVisibility(View.GONE);
        login_Button = findViewById(R.id.login_Button_ID);
        logout_Button = findViewById(R.id.logout_Button_ID);
        logout_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firebaseAuth.signOut();
            }
        });
        login_Button.setVisibility(View.VISIBLE);
        login_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {
                    startLogin();
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, 0);
                    startLogin();
                } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    startLogin();
                } else {
                    Toast.makeText(getBaseContext(), "Permission Deny", Toast.LENGTH_LONG).show();
                }
            }
        });
        // Configure Google Sign In
        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() != null) {
                    login_Button.setVisibility(View.GONE);
                    after_loginData.setVisibility(View.VISIBLE);
                    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(mActivity);
                    google_userDetails.setText("User GID: " + account.getId() + "\nUser Name: " + account.getDisplayName() + "\nEmail Address: " + account.getEmail());
                } else if (firebaseAuth.getCurrentUser() == null) {
                    login_Button.setVisibility(View.VISIBLE);
                    after_loginData.setVisibility(View.GONE);
                }
            }
        };
    }

    void startLogin() {
        dialog = ProgressDialog.show(mActivity, "",
                "Loading. Please wait...", true);
        startLoadingMethod(true);
        signIn();
    }

    private void signIn() {
        //Intent signInIntent=Auth.GoogleSignInApi
        Intent signInIntent = GoogleSignIn.getClient(this, gso).getSignInIntent();
        startActivityForResult(signInIntent, googleLoginCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == googleLoginCode) {
            startLoadingMethod(false);
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                after_loginData.setVisibility(View.VISIBLE);
                login_Button.setVisibility(View.GONE);
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
                google_userDetails.setText("User GID: " + account.getId() + "\nUser Name: " + account.getDisplayName() + "\nEmail Address: " + account.getEmail());
                //firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Toast.makeText(getBaseContext(), "Google sign in failed : " + e.getStackTrace(), Toast.LENGTH_LONG).show();
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        firebaseAuth.addAuthStateListener(authStateListener);
    }

    void startLoadingMethod(boolean isloading) {
        if (isloading) {
            dialog.show();
        } else {
            dialog.hide();
        }
    }
}

 

for the retest check in your dependencies in App level Gradle, you should have below dependencies

implementation 'com.google.android.gms:play-services-auth:16.0.0'
implementation 'com.google.firebase:firebase-auth:16.0.3'
implementation "com.google.android.gms:play-services-gcm:15.0.1"

 

and you have found one more file in your App folder of the Android project that is very important which is implemented from the firebase  google-services.json

so everything is set now Run your Android Application your Google Login API is working Now.