Integrating Google Sign-In into Android app – Sample example tutorial

By | May 27, 2020

What is google sign in: by integrating google sign in our app we can login a user by their existing google account and get the user information Like Profile picture,User Name,Email and other details so that we can identify a user.

In this tutorial, we will create a simple android app by  implementing google sign-in to  fetch user’s name &  profile picture, display them on simple layout  and add a button to finally sign out.

STEP 1:

-Create a new project in android studio name it as Testing and package name is com.khushi.testing.

-And i have activity named MainActivity.java and its layout file name is activity_main.xml.

STEP 2: Add Google Play Services –

In your project’s top-level build.gradle file, ensure that Google’s Maven repository is included:

allprojects {
repositories {
google()

// If you're using a version of Gradle lower than 4.1, you must instead use:
// maven {
// url 'https://maven.google.com'
// }
}
}

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

dependencies {
//this id for google play services
 implementation 'com.google.android.gms:play-services-auth:18.0.0'
//this id for displaying user image in ImageView
implementation 'com.github.bumptech.glide:glide:3.7.0'
 

STEP 3: Add this permission in AndroidManifest File-

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

STEP 4: Create a Google API Console Project-

To create a Google API console project,go to Configure a Project, and specify your Project name,Android App package name and SHA-1.(you can find SHA- in your android studio click on Gradle>Project Name>Tasks>Android>SigningReport)

 

 

 

And download credentials.json and paste it into your project’s app folder in android studio.

STEP 5: Creating App Layout ,in your .Xml file

I simply create :Buttons for sign-in,sign-out,Textview for user name, email and ImageView for profile pic.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

 <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="112dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />

 <Button android:id="@+id/btn_sign_out" android:layout_width="131dp" android:layout_height="52dp" android:layout_marginStart="140dp" android:layout_marginLeft="140dp" android:layout_marginTop="560dp" android:text="Sign Out" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />

 <ImageView android:id="@+id/imgProfilePic" android:layout_width="141dp" android:layout_height="126dp" android:layout_marginStart="132dp" android:layout_marginLeft="132dp" android:layout_marginTop="232dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@mipmap/ic_launcher" />

 <TextView android:id="@+id/txtName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="140dp" android:layout_marginLeft="140dp" android:layout_marginTop="180dp" android:text="TextView" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/imgProfilePic" />

 <TextView android:id="@+id/txtEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="140dp" android:layout_marginLeft="140dp" android:layout_marginTop="72dp" android:text="TextView" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/txtName" />
</androidx.constraintlayout.widget.ConstraintLayout>

STEP 6: Now open MainActivity.java and do the below modifications-

In your sign-in activity’s onCreate method, configure Google Sign-In to request the user data required by your app. create a GoogleSignInOptions object with the DEFAULT_SIGN_IN parameter. To request users’ email addresses as well, create the GoogleSignInOptions object with the requestEmail option.

6.1 Configure Google Sign-in and the GoogleSignInClient object

GoogleSignInClient mGoogleSignInClient;
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
GoogleSignInClient mGoogleSignInClient;
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

6.2 SignIn()…Starting the intent prompts the user to select a Google account to sign in with and call OnActivityResult().

6.3   @Override onActivityResult()…After the user signs in, you can get a GoogleSignInAccount object for the user in the activity’s onActivityResult method.

6.4 handleSignInResult()…onActivityResult() call this method with result whether user signed in successfully or not. if success we can get the user’s account details.

6.5 UpdateUI()…User can call this method when he wants changes on ui when account login/logout e.g: display/hide buttons.

6.6 SignOut()… Simply sign out from your google account and you can update UI accordingly.

6.7 @Override OnStart()…Check for existing Google Sign In account, if the user is already signed in the GoogleSignInAccount will be null.

package com.khushi.testing;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
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.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    GoogleSignInOptions gso;
    GoogleSignInClient mGoogleSignInClient;
    SignInButton signInButton;
    Button btnSignOut;
    private ImageView imgProfilePic;
    private TextView txtName, txtEmail;
    private static final int RC_SIGN_IN =7;
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Configure sign-in to request the user's ID, email address, and basic
        // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
        // Build a GoogleSignInClient with the options specified by gso.
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
       signInButton.setOnClickListener(this);
        btnSignOut = (Button) findViewById(R.id.btn_sign_out);
        btnSignOut.setOnClickListener(this);
        imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
        txtName = (TextView) findViewById(R.id.txtName);
        txtEmail = (TextView) findViewById(R.id.txtEmail);

    }

    @Override

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            case R.id.btn_sign_out:
                signOut();
                break;
            // ...
        }

    }

    private void signIn() {
      //  Toast.makeText(this,"signIn method called",Toast.LENGTH_SHORT).show();
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //  Toast.makeText(this,"OnActivityResultCalled"+requestCode,Toast.LENGTH_SHORT).show();
        // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task&lt;GoogleSignInAccount&gt; task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }
    private void handleSignInResult(Task&lt;GoogleSignInAccount&gt; completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            String personName = account.getDisplayName();
            String personPhotoUrl = account.getPhotoUrl().toString();
            String email = account.getEmail();
            txtName.setText(personName);
            txtEmail.setText(email);
            Glide.with(getApplicationContext()).load(personPhotoUrl)
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgProfilePic);
            // Signed in successfully, show authenticated UI.

            updateUI(account);
        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode()+"\n"+e.getLocalizedMessage()+"\nMEssg: "+e.getMessage());
            updateUI(null);
        }
    }
    private void updateUI(GoogleSignInAccount account) {

        if(account==null)
        {
            // Toast.makeText(this, "not signed in", Toast.LENGTH_SHORT).show();
            signInButton.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.GONE);
            imgProfilePic.setVisibility(View.GONE);
            txtEmail.setVisibility(View.GONE);
            txtName.setVisibility(View.GONE);
            Toast.makeText(this,"please sign in",Toast.LENGTH_SHORT).show();
        }
        else {
            signInButton.setVisibility(View.GONE);
            imgProfilePic.setVisibility(View.VISIBLE);
            txtEmail.setVisibility(View.VISIBLE);
            txtName.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.VISIBLE);
            Toast.makeText(this,"you are signed in",Toast.LENGTH_SHORT).show();
        }

    }
    private void signOut() {
        mGoogleSignInClient.signOut()
                .addOnCompleteListener(this, new OnCompleteListener&lt;Void&gt;() {
                    @Override
                    public void onComplete(@NonNull Task&lt;Void&gt; task) {
                        updateUI(null);
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        // Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        updateUI(account);
    }

}

1,161 total views, 11 views today

(Visited 317 times, 3 visits today)