Google Login and Logout in Android With Firebase (Kotlin Implementation)

Tanishq Sehgal
The Startup
Published in
8 min readNov 2, 2020

--

A detailed explanation of how to implement Google Login and Logout in your Android App

Google Sign-In is a secure way to authenticate users in your apps. It reduces the hassle of dealing and handling those extra passwords by the user to get authenticated to the app. One can use the same Google login option to authenticate to multiple apps. This saves us from clicking that “Forgot Password?” button every time someone forgets the login password.

These days most of the apps we use have an option of Google Login for user authentication thereby the user experience easy and effective.

In this article, I am going to demonstrate the implementation of Google Login-and Logout using Firebase in Kotlin using Android Studio. Let’s get started:)

Step 1: Create an Android Studio project by selecting an empty activity. You can name your project in any way you want, I have named it GoogleLoginLogOut. Do not forget to select the language as Kotlin. Select the minimum SDK version 21 ie. Android 5.0 Lolipop.

Empty Activity Selected for android project
Project is named and Kotlin language is selected

Step 2: Add Firebase to your Android Studio Project as shown below.

  1. Click on tools, then click on Firebase.

2. Click on Authentication in the Firebase Assistant and then select Email and Password Authentication. After this, you will see the option for Connecting to Firebase, you need to click on that option.

3. Now you’ll be directed to the firebase console page on your browser where you have to create a project by clicking on “Add Project”. Then click on continue. Kindly disable Google Analytics for this project. We don't need it for now.

4. Click on “Create Project” and click on “Connect”. Now you will see that Firebase is connected to your Android Studio Project.

Click on “Add Firebase Authentication to your app” to set up the dependencies correctly.

This confirms that Firebase is connected to your Project
Dependencies set up correctly

Step 3: To enable the authentication provider, we need to include some dependencies in the App Level Gradle file which are given as follows.

dependencies {    // Import the BoM for the Firebase platform    implementation platform('com.google.firebase:firebase-bom:26.0.0')

// Declare the dependency for the Firebase Authentication library
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation 'com.google.firebase:firebase-auth-ktx'

// Also declare the dependency for the Google Play services library and specify its version
implementation 'com.google.android.gms:play-services-auth:18.1.0'
}
// Or you can also use the following dependencies dependencies {implementation 'com.google.firebase:firebase-auth:20.0.0'
implementation 'com.google.android.gms:play-services-auth:18.1.0'
}

Add the following dependency to Project Level Gradle

buildscript {
ext.kotlin_version = "1.4.0"
repositories {
google()
jcenter()
}
dependencies {

classpath 'com.google.gms:google-services:4.3.4'
}
}

allprojects {
repositories {
google()
jcenter()
}
}

Click on “Sync Now” after adding these dependencies.

You can see that the build is successful and dependencies are set up correctly. To authenticate your client, add your SHA-1 to your firebase project in the firebase console. To obtain your SHA-1 fingerprint, run the signing report in Android Studio.

Now, go to the firebase console and open your project there. Click on project settings and then click on “Add a fingerprint” and paste your SHA-1 fingerprint there and save it.

Step 4: Now we need to select the Sign-In Method. For this, go to Authentication in Firebase Console on your browser, click on the “Sign-In Method”. You’ll see the option for Google Sign-In. Enable it, add your email id and save it.

This enables Google Login on your Firebase Project.

Step5: Now we can start implementing Google Sign-In in our Android Studio project by adding some code.

Before integrating google sign-in, let's work a little bit on the UI of the app. We need to create an empty activity named LoginScreen.kt that takes us to the MainActivity of our app.

Create an empty Activity — LoginScreen.kt

Set the LoginScreen.kt as the launcher activity while creating it.

Now for the UI of the login screen, we need to add the following code in activity_login_screen.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=".LoginScreen">

<View
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="450dp"
android:background="@android:color/holo_orange_light"
app:layout_constraintTop_toTopOf="parent" />

<androidx.cardview.widget.CardView
android:id="@+id/cardView2"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_margin="30dp"
android:background="#d3d3d3"
app:cardCornerRadius="30dp"
app:cardElevation="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="@+id/view"
tools:layout_editor_absoluteX="30dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="100dp">

<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:src="@drawable/ic_baseline_person_pin_24" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Google Login"
android:textAlignment="center"
android:textSize="32sp" />

<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="20dp"
app:cardElevation="30dp"
android:layout_gravity="center"
android:layout_margin="50dp"
android:clickable="true"
android:focusable="true"
android:id="@+id/Signin">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:padding="10dp">

<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="start"
android:src="@drawable/google_button"
android:layout_marginEnd="5dp"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Sign in with Google"
android:textAlignment="center"
android:textSize="16sp"
android:textColor="@android:color/white"/>

</LinearLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>

</androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

This is how our login screen looks after adding the above XML code. By clicking on the button we will be directed to MainActivity.kt where we will implement Google Logout.

Step 6: Now we will be integrating Google Login in our app. Add the following code to LoginScreen.kt

  1. First, we get the shared instance of the FirebaseAuth object, Req Code and GoogleSigninClient in LoginScreen.kt
lateinit var mGoogleSignInClient: GoogleSignInClient
val Req_Code:Int=123
val firebaseAuth= FirebaseAuth.getInstance()

2. We have to configure the GoogleSignInOptions object, call requestIdToken in LoginScreen.kt

// Configure Google Sign In inside onCreate mentod
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
// getting the value of gso inside the GoogleSigninClient
mGoogleSignInClient=GoogleSignIn.getClient(this,gso)
// initialize the firebaseAuth variable firebaseAuth= FirebaseAuth.getInstance()

You must pass the server's client ID to the requestIdToken method. This is done in the following way:

Click on this page to get the server’s client ID. Then click on “Configure Project”. Then select your project in the drop-down list. In my case it is GoogleLoginLogout.

Copy your package name and SHA-1 fingerprint and paste in the following dialog box where you have to configure the Auth Client.

Copy the client ID after clicking on “Create” and pass it inside the requestIdToken method as a String resource.

Step 7: After this, we have to create signInGoogle() function, onActivityResult() and handleResult() function LoginScreen.kt.

// signInGoogle() functionprivate  fun signInGoogle(){

val signInIntent:Intent=mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent,Req_Code)
}
// onActivityResult() function : this is where we provide the task and data for the Google Account override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode==Req_Code){
val task:Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
handleResult(task)
}
}
// handleResult() function - this is where we update the UI after Google signin takes place private fun handleResult(completedTask: Task<GoogleSignInAccount>){
try {
val account: GoogleSignInAccount? =completedTask.getResult(ApiException::class.java)
if (account != null) {
UpdateUI(account)
}
} catch (e:ApiException){
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show()
}
}
// UpdateUI() function - this is where we specify what UI updation are needed after google signin has taken place.private fun UpdateUI(account: GoogleSignInAccount){
val credential= GoogleAuthProvider.getCredential(account.idToken,null)
firebaseAuth.signInWithCredential(credential).addOnCompleteListener {task->
if(task.isSuccessful) {
SavedPreference.setEmail(this,account.email.toString()) SavedPreference.setUsername(this,account.displayName.toString())
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
override fun onStart() {
super.onStart()
if(GoogleSignIn.getLastSignedInAccount(this)!=null){
startActivity(Intent(this, MainActivity::class.java))
finish()
}

}

Step 8: Make a Kotlin object named SavedPreference in order to access the user credentials anywhere in the app and add the following code there:

object SavedPreference {

const val EMAIL= "email"
const val USERNAME="username"

private fun getSharedPreference(ctx: Context?): SharedPreferences? {
return PreferenceManager.getDefaultSharedPreferences(ctx)
}

private fun editor(context: Context, const:String, string: String){
getSharedPreference(
context
)?.edit()?.putString(const,string)?.apply()
}

fun getEmail(context: Context)= getSharedPreference(
context
)?.getString(EMAIL,"")

fun setEmail(context: Context, email: String){
editor(
context,
EMAIL,
email
)
}

fun setUsername(context: Context, username:String){
editor(
context,
USERNAME,
username
)
}

fun getUsername(context: Context) = getSharedPreference(
context
)?.getString(USERNAME,"")

}

Step9: Now we have to call the signInGoogle() method on click of the button in the login screen that we made earlier. This is done in on create method of LoginScreen.kt.

Signin.setOnClickListener{ view: View? ->
signInGoogle()
}

Step10: To ensure that we directly reach MainActivity when the account is Logged in, we add the following code in LoginScreen.kt as well:

override fun onStart() {
super.onStart()
if(GoogleSignIn.getLastSignedInAccount(this)!=null){
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
// if you do not add this check, then you would have to login everytime you start your application on your phone.

This completes Google Login Implementation in Android Studio using Firebase. When I log in to my app using my Gmail ID, it takes me to the MainActivity and my user credentials automatically update in the Firebase Authentication user list as follows.

Step11: Since GoogleLogin is implemented, we will now proceed with the implementation of Google Logout.

Inside activity_main.xml create a button which when clicked, logs out the user from the app. Add the following code to activity_main.xml for the same.

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

<Button
android:id="@+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:textSize="20sp"
android:padding="10dp"
android:foreground="?android:attr/selectableItemBackground"
android:textColor="@android:color/holo_orange_light"
android:background="@android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step12: Now we will implement the Logout on click of the “LOGOUT” button. This directs us to the login screen again. The following code is written in MainActivity.kt to make the Logout feature functional.

// declare the GoogleSignInClientlateinit var mGoogleSignInClient: GoogleSignInClient
// val auth is initialized by lazy private val auth by lazy {
FirebaseAuth.getInstance()
}

We have to configure the GoogleSignInOptions object, call requestIdToken in Mainactivity.kt as follows:

val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleSignInClient= GoogleSignIn.getClient(this,gso)
// pass the same server client ID used while implementing the LogIn feature earlier.

After this, we will implement logout on click of the LOGOUT button

logout.setOnClickListener {
mGoogleSignInClient.signOut().addOnCompleteListener {
val intent= Intent(this, LoginScreen::class.java)
startActivity(intent)
finish()
}
}

Clicking this logs us out of our app and so that we can log in again with some other Gmail ID or the same ID if we want.

So this was the entire implementation of Google login and Google logout using Firebase. You can integrate this feature in your android apps to ease out user authentication.

Kindly try implementing this feature and tell me how did you like the tutorial.

Leave your suggestions in the comments below about what tutorials should I make further.

If you liked the implementation please do not forget to click the 👏 button. Thank you:)

Kindly check the project on my Github account for more reference

https://github.com/TanishqSehgal7/GoogleLogInLogOut

--

--

Tanishq Sehgal
The Startup

Android App Developer. I love discussing technologies and advancements in the tech world.