X

Android Google Login Integration Tutorial For Beginners

 

Android google login :

Android google login tutorial will guide you through the process of integrating login process in your app.We can use the google login credentials in your app to make user login.

Now a days there are many apps and websites where they require user credentials to maintain minimum security so we need to create a credentials in most of the apps.

So integrating them with android Google Login we can easily access these apps and websites with our google account by providing them the required information.

Also this is the safest way because we can remove the access when we don’t require them any more from google account.

And no need to remember or maintain multiple accounts and their credentials.

We can get the user details from the google like name, email user profile picture from their account seeking the permission from the user.

 

Android google login video tutorial :

Go through the below tutorial for more details on implementation.

 

Project Structure :

This image depicts the android google login project structure implementation

 

activity_main.xml :

Add a google login button provided by google and add a default button to ake logout of the user.

<?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="116dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/sign_out_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="logout"
        android:visibility="gone"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        android:background="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/sign_in_button"
        app:layout_constraintVertical_bias="0.253" />


</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.kt :

Add variables RC_SIGN_IN and GoogleSignInClient

private val RC_SIGN_IN = 100

private lateinit var mGoogleSignInClient: GoogleSignInClient

 

Specify the variables here you need to specify the Google Key here which you generated in google api console

val gso =
    GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken("add you key here")
        .requestEmail()
        .build()

 

Initialize the Google Client

mGoogleSignInClient = GoogleSignIn.getClient(this,gso)

 

Specify the Google Button Size

sign_in_button.setSize(SignInButton.SIZE_STANDARD)

 

Set onClickListeners for both sign_in and sign_out button

sign_in_button.setOnClickListener(View.OnClickListener {
    signIn();
});

sign_out_button.setOnClickListener(View.OnClickListener {
    signOut();
});

 

OnStart of the app we can check the user details if the user is logged in and updateUI

override fun onStart() {
    super.onStart()

    val account = GoogleSignIn.getLastSignedInAccount(this)
    updateUI(account)
}

 

Define the SignIn and SignOut methods

private fun signIn() {
    val signInIntent: Intent = mGoogleSignInClient.getSignInIntent()
    startActivityForResult(signInIntent, RC_SIGN_IN)
}

 

private fun signOut() {
    mGoogleSignInClient.signOut()
        .addOnCompleteListener(this) {

            sign_out_button.visibility = View.GONE
            sign_in_button.visibility = View.VISIBLE
        }
}

 

OnActivityResult to be specified to handle the data after successful login

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // 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.
        val task =
            GoogleSignIn.getSignedInAccountFromIntent(data)
        handleSignInResult(task)
    }
}

 

Get the account details of the user

private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
    try {
        val account =
            completedTask.getResult(ApiException::class.java)

        // Signed in successfully, show authenticated UI.
        updateUI(account)
    } catch (e: ApiException) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.w("Status", "signInResult:failed code=" + e.statusCode)
        updateUI(null)
    }
}

 

Update the UI with user details after fetching the details

private fun updateUI(account: GoogleSignInAccount?) {

    sign_out_button.visibility = View.VISIBLE
    sign_in_button.visibility = View.GONE

    Log.d("Account Details",""+account?.displayName)
    Toast.makeText(this,""+account?.displayName,Toast.LENGTH_SHORT).show()
}

 

FullCode :


Providing the full code for android google login integration

package com.abhi.googlelogin

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
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.Task
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    private val RC_SIGN_IN = 100

    private lateinit var mGoogleSignInClient: GoogleSignInClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val gso =
            GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("add you key here")
                .requestEmail()
                .build()

        mGoogleSignInClient = GoogleSignIn.getClient(this,gso)


        sign_in_button.setSize(SignInButton.SIZE_STANDARD)

        sign_in_button.setOnClickListener(View.OnClickListener {
            signIn();
        });

        sign_out_button.setOnClickListener(View.OnClickListener {
            signOut();
        });

    }

    override fun onStart() {
        super.onStart()

        val account = GoogleSignIn.getLastSignedInAccount(this)
        updateUI(account)
    }

    private fun signIn() {
        val signInIntent: Intent = mGoogleSignInClient.getSignInIntent()
        startActivityForResult(signInIntent, RC_SIGN_IN)
    }

    private fun signOut() {
        mGoogleSignInClient.signOut()
            .addOnCompleteListener(this) {

                sign_out_button.visibility = View.GONE
                sign_in_button.visibility = View.VISIBLE
            }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 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.
            val task =
                GoogleSignIn.getSignedInAccountFromIntent(data)
            handleSignInResult(task)
        }
    }

    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            val account =
                completedTask.getResult(ApiException::class.java)

            // Signed in successfully, show authenticated UI.
            updateUI(account)
        } catch (e: ApiException) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.w("Status", "signInResult:failed code=" + e.statusCode)
            updateUI(null)
        }
    }

    private fun updateUI(account: GoogleSignInAccount?) {

        sign_out_button.visibility = View.VISIBLE
        sign_in_button.visibility = View.GONE

        Log.d("Account Details",""+account?.displayName)
        Toast.makeText(this,""+account?.displayName,Toast.LENGTH_SHORT).show()
    }

}

 

If you are having any queries on android google login do let me know in comment section below.

 

 

 

abhishek:
Related Post

This website uses cookies.