Kotlin Google Sign in Activity with Layout Example

 Kotlin

package com.example.googlesignin

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
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.api.ApiException
import com.google.android.gms.tasks.Task
import com.example.googlesignin.databinding.ActivityMainBinding 

 // Import your binding class

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding // Declare binding variable
    private lateinit var googleSignInClient: GoogleSignInClient
    private lateinit var signInLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater) // Initialize binding
        setContentView(binding.root) // Set the content view

        // Configure Google Sign In
        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail() // Request email access
            .build()

        googleSignInClient = GoogleSignIn.getClient(this, gso)

        signInLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
                handleSignInResult(task)
            } else {
                Toast.makeText(this, "Sign in cancelled", Toast.LENGTH_SHORT).show()
            }
        }

        // Set click listener for the sign-in button
        binding.signInButton.setOnClickListener {
            signIn()
        }


        // Check for existing signed-in account (optional)
        val account = GoogleSignIn.getLastSignedInAccount(this)
        if (account != null) {
            // Signed in, update UI
            updateUI(account)
        }
    }


    private fun signIn() {
        val signInIntent = googleSignInClient.signInIntent
        signInLauncher.launch(signInIntent)

    }

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

            // Signed in successfully, update 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("Google Sign In", "signInResult:failed code=" + e.statusCode)
            Toast.makeText(this, "Sign in failed", Toast.LENGTH_SHORT).show()
            updateUI(null)
        }
    }

    private fun updateUI(account: GoogleSignInAccount?) {
        if (account != null) {
            // Signed in, show appropriate UI
            binding.signInButton.text = "Signed in as ${account.displayName}"
            // Example: Start a new activity or update views
        } else {
            // Signed out, show sign-in button
            binding.signInButton.text = "Sign In with Google"
        }
    }
}

activity_main.xml (Example Layout):

XML
<?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/signInButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Key improvements and explanations:

  • View Binding: Uses ActivityMainBinding for cleaner and safer view access. Make sure to enable view binding in your module's build.gradle file:
Gradle
android {
    ...
    buildFeatures {
        viewBinding true
    }
}
  • ActivityResultLauncher: Uses the modern and recommended ActivityResultLauncher API for handling the sign-in intent result. This replaces the deprecated onActivityResult.

  • Clearer Error Handling: Improved error handling in handleSignInResult with logging and a Toast message.

  • UI Updates: The updateUI function now updates the button text to reflect the sign-in status. It's a good place to add code to navigate to another activity or update other UI elements after successful sign-in.

  • Optional Signed-In Account Check: Includes a check for an existing signed-in account in onCreate. This way, if the user has previously signed in, you can directly update the UI without requiring them to click the sign-in button again.

  • Comments and Structure: Added more comments and improved the code structure for better readability.

Steps to integrate Google Sign-In:

  1. Add Dependencies: Add the Google Sign-In dependency to your build.gradle file:
Gradle
dependencies {
    implementation 'com.google.android.gms:play-services-auth:20.6.0' // Or latest version
    ...
}
  1. SHA-1 Fingerprint: You'll need to get the SHA-1 fingerprint of your signing certificate (debug and release). This is crucial for Google to recognize your app. See the official Google documentation for how to generate this: https://developers.google.com/android/guides/auth/google-signin

  2. Firebase Console (or Google Cloud Console):

    • Go to the Firebase console (or Google Cloud Console if you prefer).
    • Create or select your project.
    • In the "Authentication" section, enable Google Sign-In.
    • Add your SHA-1 fingerprint(s) (both debug and release) to the project settings.
  3. Code Implementation: Implement the Kotlin code provided above in your Activity.

  4. Layout: Create the layout file (activity_main.xml in this example) with the SignInButton or any other button you want to use for sign-in.

Remember to replace "Sign In with Google" with your actual button's text if you're not using the standard SignInButton. Also, handle the signed-in user information (like account.displayName, account.email, etc.) appropriately in the updateUI function or after successful sign-in.

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos