Native Mobile App Development With Java

Android Google Signin example Java

25-Sep-2024

Android Google Signin example Java


** Note Some Images text are blank for security purpose


1/ Create a Project: Firebase Google Login

2/  Create a Firebase project

3/ Connect Firebase: You can connect Firebase via Android Studio Firebase Tool Assistance or Manually. For this project, I create and connect the project manually.


   3.1/ After creating the project in Firebase first click on the Android icon to connect the app with your project. Here, provide your app package name and click next, next, and lastly, go to the console.


  3.2/ From the Firebase project setting copy the App ID store it in a string values file and give a name for the App ID value ( In my case google_app_id)





<string name="google_app_id">1:788y8y987:android:asdfaf328798asdf</string>



 3.3/ Generate SHA keys in Android Studio Click on the gradle tool window click the terminal icon write the code (gradle signingReport) and hit enter after that you can see the sha1 and sha256 code in the terminal window. Copy sha1 and sha256 one after one and add them to your Firebase project setting by clicking on add fingerprint










3.4/ Enable Authentication from the build option in your Firebase Project and click the option sign-in method. then click on add new provider then select google.

after that enable and save. Now can see the Google provider is added again click this time you can see the web client ID copy and store it in string values



<string name="web_client_id">87698-98689asfdasd89f7asd98f.apps.googleusercontent.com</string>














lastly, go to your project setting you can download the google-service.json file copy and paste it into your app folder in your project


4/ Update build.gradle file project level 




// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
}
buildscript {
dependencies {
classpath("com.google.gms:google-services:4.4.2")
}
}



5/ Add dependencies to the build.gradle file app level



// firebase bom
implementation(platform("com.google.firebase:firebase-bom:33.2.0"))

//firebase auth
implementation("com.google.firebase:firebase-auth")

// Google Play services
implementation("com.google.android.gms:play-services-auth:21.2.0")


and add another line bottom of the file 




apply(plugin = "com.google.gms.google-services")



full build.gradle app level code in my project is 





plugins {
alias(libs.plugins.android.application)

}

android {
namespace = "com.example.firebasegooglelogin"
compileSdk = 34

defaultConfig {
applicationId = "com.example.firebasegooglelogin"
minSdk = 26
targetSdk = 34
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}

dependencies {

implementation(libs.appcompat)
implementation(libs.material)
implementation(libs.activity)
implementation(libs.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)

// firebase bom
implementation(platform("com.google.firebase:firebase-bom:33.2.0"))

//firebase auth
implementation("com.google.firebase:firebase-auth")

// Google Play services
implementation("com.google.android.gms:play-services-auth:21.2.0")


}

apply(plugin = "com.google.gms.google-services")


** Note that this syntax is for Kotlin gradle if you are using Grovy then your code format will be different.


6/ Now your coding part will be started Modify your activity_main.xml file


 don't forget to add a google_icon to your res/drawable folder




<?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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:id="@+id/googleSignInBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/google_icon"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign in with Google"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginStart="16dp"
/>
</LinearLayout>



</androidx.constraintlayout.widget.ConstraintLayout>



7/ Modify your MainActivity.Java file 




package com.example.firebasegooglelogin;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
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.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;


public class MainActivity extends AppCompatActivity {

private LinearLayout googleSignInBtn;
private GoogleSignInClient googleSignInClient;
private FirebaseAuth auth;
private static final int RC_SIGN_IN = 11112;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);


FirebaseApp.initializeApp(MainActivity.this);
auth = FirebaseAuth.getInstance();

googleSignInBtn = findViewById(R.id.googleSignInBtn);
auth = FirebaseAuth.getInstance();


GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.web_client_id))
.requestEmail()
.build();


googleSignInClient = GoogleSignIn.getClient(MainActivity.this, gso);

googleSignInBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
if (task.isSuccessful()) {
try {
GoogleSignInAccount googleSignInAccount = task.getResult(ApiException.class);
if (googleSignInAccount != null) {
AuthCredential credential = GoogleAuthProvider.getCredential(googleSignInAccount.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(MainActivity.this, innerTask -> {
if (innerTask.isSuccessful()) {
FirebaseUser user = auth.getCurrentUser();
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
intent.putExtra("email", user.getEmail());
startActivity(intent);
finish();
} else {
}
});
}
} catch (ApiException e) {
e.printStackTrace();
}
}
}
}
}


8/ Modify AndroidManifest.xml





<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FirebaseGoogleLogin"
tools:targetApi="31">
<activity
android:name=".MainActivity2"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<meta-data
android:name="com.google.android.gms.auth.api.gmscore.APP_ID"
android:value="@string/google_app_id" />
</application>

</manifest>


9/Check your string file




<resources>
<string name="app_name">Firebase Google Login</string>
<string name="web_client_id">87658463-934875sdfadf.apps.googleusercontent.com</string>
<string name="google_app_id">1:7657578:android:jyfgyk76576</string>
</resources>


10/ Create Another Activity (In my case I set the name MainActivity2 )


11/ Modify your activity_main2.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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity2">

<TextView
android:id="@+id/emailTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sohan@gmail.com"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginTop="50dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="You are login with the above email id"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="@id/emailTxt"
app:layout_constraintStart_toStartOf="@id/emailTxt"
app:layout_constraintTop_toBottomOf="@+id/emailTxt" />


</androidx.constraintlayout.widget.ConstraintLayout>



12/ Modify the MainActivity2.java file 




package com.example.firebasegooglelogin;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity2 extends AppCompatActivity {

private TextView emailTxt;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main2);

Intent intent = getIntent();

emailTxt = findViewById(R.id.emailTxt);

emailTxt.setText(intent.getStringExtra("email"));

}
}



Output:










Comments