Integrate Google Sign In Into Android

FrugalisMinds

Author - FrugalisMinds

Integrate Google Sign Into Android:-

We will integrate Google sign in into  Android app. Google let users sign in through their Gmail account in their Android app.Google signing we get all the user details such as profile details, image, contacts very easily and quickly.

Integrating Google sign in into your Android app lets users sign quickly without the need for the complex registration process.

//pagead2.googlesyndication.com/pagead/js/adsbygoogle

Configure Google Sign in:-

In order to integrate Google Sign In we need to first go ahead and set up the project on the Google developer console. We need to add  google-services.json file to your project's app folder. Please visit on the link here.

  1. This will take you to link where you will be prompted to enter app name and package name as shown below.
  2. Enter the project name if not create a project.
  3. Then enter the project package name as per your choice.
  4. Click on choose and now we get the next screen where we need to add our SHA1 key.

andsroid 300x145

Generate SHA1 Key :-

Now we need Java keytool to generate SHA1 fingerprint so, in order to use Java keytool, you must have Java installed on your machine.Then you go to your command prompt and type the following command below to generate the SHA1 fingerprint.Its super easy.

You will get something like this as output:-

finger 300x137

Copy SHA1 value and paste in the next screen.

final 300x185

Go to next and Click on download google-services.json and download the JSON file.

Create and Setup Project :

Create the New project and Enter same package name as you have configured before.

Add com.google.android.gms:play-services-auth:11.0.2 dependency to your app level build file and apply plugin 'com.google.gms.google-services' on the bottom of your app level build folder.

    compile fileTree(dir: 'libs', include: \['\*.jar'\])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.2'

    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Open project level build file and add following

        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

Create activity_main.xml:-

we are adding two buttons one for SignIn and other for SignOut.

">
">"><LinearLayout 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"
    tools:context="org.cravez.in.MainActivity">

    <LinearLayout
        android:layout\_width="match\_parent"
        android:layout\_height="match\_parent"
        android:layout\_marginTop="120dp"
        android:layout\_weight="1"
        android:orientation="horizontal">

        <Button
            android:id="@+id/signin"
            android:layout\_width="wrap\_content"
            android:layout\_height="wrap\_content"
            android:layout\_weight="1"
            android:text="SignIn"
            tools:layout\_editor\_absoluteX="-111dp"
            tools:layout\_editor\_absoluteY="463dp" />

        <Button
            android:id="@+id/signout"
            android:layout\_width="wrap\_content"
            android:layout\_height="wrap\_content"
            android:layout\_weight="1"
            android:text="Signout" />
    </LinearLayout>

</LinearLayout>

Configure Auth2.0 Client Id :-

you can skip this if you want to do signin just for demo purpose but, if you want to do a backend validation we need google signin to generate a token and send to our REST server which will do the validations and authentication.  This step is needed if you want to pass the currently signed-in user to a backend server, send the ID token to your backend server and validate the token on the server.Visit Google developer console  . Select the appropriate project and click on Credentials.

You see list of  OAuth 2.0 client IDs, select Web client (Auto-created for Google Sign-in) and copy the client id and store it in a string resource as

your copied web client key ">
your copied web client key ">your copied web client key ">

We are using this key when we create an object of  _GoogleSignInOptions _ as below in MainActivity.java

Now Open your MainActivity.java and add below set of code step by step.

In OnCreate Method add GoogleSigninoptions object create a method called signinClick() ,handleSignInResult().

        .requestIdToken(getString(R.string.server\_clientid))
        .requestProfile()
        .requestEmail()
        .build();
        .enableAutoManage(this, this)
       .addApi(Auth.GOOGLE\_SIGN\_IN\_API, gso)
       .build();
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC\_SIGN\_IN);
}

MainActivity.java:-

We are receiving token after the user signed in in handleSignInResult and now use this token to validate. Please visit the link here to check google implementation here .

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

public class MainActivity extends AppCompatActivity implements  GoogleApiClient.OnConnectionFailedListener{

    Button signin,signout;
    GoogleApiClient mGoogleApiClient;
    private static final int RC\_SIGN\_IN = 9001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity\_main);
        signin=(Button)findViewById(R.id.signin);
        signout=(Button)findViewById(R.id.signout);
        signout.setVisibility(View.GONE);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT\_SIGN\_IN)
                .requestIdToken(getString(R.string.server\_clientid))
                .requestProfile()
                .requestEmail()
                .build();

         mGoogleApiClient = new GoogleApiClient.Builder(this)
                 .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE\_SIGN\_IN\_API, gso)
                .build();

        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "hii", Toast.LENGTH\_SHORT).show();
                signInClick();

            }
        });

        signout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                        new ResultCallback<Status>() {
                            @Override
                            public void onResult(Status status) {
                                // \[START\_EXCLUDE\]
                                if(status.isSuccess()){
                                    signin.setVisibility(View.VISIBLE);
                                    signout.setVisibility(View.GONE);
                                }

                                // \[END\_EXCLUDE\]
                            }
                        });
            }
        });

    }

    private void signInClick () {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC\_SIGN\_IN);
    }

    @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 onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    private void handleSignInResult(GoogleSignInResult result) {

        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            String idToken = acct.getIdToken();
            Log.d("DD", idToken);
            signout.setVisibility(View.VISIBLE);
            signin.setVisibility(View.GONE);

        }
    }

}

Output:-

crvz 300x234

Download Code