Firebase

Google Sign in using firebase Android

Pinterest LinkedIn Tumblr

In this blog, I’m going to show you adding Google Sign In using firebase in your android app. It very easy to do just follow below step. So let’s get started.

Step of Implementation Google Authentication
  • Create an android project
  • Setup and add project on firebase console.
  • Enable Google Sign In
  • Add SHA and 256 keys to the app on firebase console. (Required step for Google Sign In )
  • Add authentication library in app-level build.gradle
  • Setup Google client
1. Create an android project

Let’s move to android studio and create a new project. In this sample application, I’m taking a package name is com.googlesigninfirebase for demonstration of Google Sign in using firebase. let’s go to next step.

2. Setup new firebase project on firebase console.

Let’s open the firebase console and add a project. For adding a project on firebase follow my previous post. Adding Firebase to Android App Manually

3. Enable Google Sign In

Select Authentication from the left panel. Go to the Sign In method and you can select Google and enable the Google SignIn. In sort ( Authentication -> Sign In Method -> Google -> Enable ).

4. Add SHA and 256 keys to the app on firebase console

This is the required step for google sign In. Now go to the android studio project. To get the signature of the app clicks the gradle on right-hand side. Now select app -> task -> android and select singingReport.

You just need to copy and paste in project setting in firebase. You have to set both keys SHA1 and SHA-256. Now come back to android studio follow next step.

Add authentication library in app-level build.gradle
 implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
 // Google Sign In SDK (only required for Google Sign In)
 implementation 'com.google.android.gms:play-services-auth:17.0.0'
Create a new activity along with layout named is LoginActivity

Open layout file and button for demonstration

<?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=".LoginActivity"
    >

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

</androidx.constraintlayout.widget.ConstraintLayout>
Open LoginActvitiy and paste following code
package com.googlesigninfirebase;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
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.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class LoginActivity extends AppCompatActivity {
  private static final String TAG = "LoginActivity";
  private static final int RC_SIGN_IN = 1001;

  GoogleSignInClient googleSignInClient;

  private FirebaseAuth firebaseAuth;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    SignInButton signInButton = findViewById(R.id.sign_in_button);
    signInButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        // Launch Sign In
        signInToGoogle();
      }
    });

    // Configure Google Client
    configureGoogleClient();
  }

  private void configureGoogleClient() {
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        // for the requestIdToken, this is in the values.xml file that
        // is generated from your google-services.json 
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();

    // Build a GoogleSignInClient with the options specified by gso.
    googleSignInClient = GoogleSignIn.getClient(this, gso);

    // Set the dimensions of the sign-in button.
    SignInButton signInButton = findViewById(R.id.sign_in_button);
    signInButton.setSize(SignInButton.SIZE_WIDE);

    // Initialize Firebase Auth
    firebaseAuth = FirebaseAuth.getInstance();
  }

  @Override
  public void onStart() {
    super.onStart();

    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = firebaseAuth.getCurrentUser();

    if (currentUser != null) {
      Log.d(TAG, "Currently Signed in: " + currentUser.getEmail());
      showToastMessage("Currently Logged in: " + currentUser.getEmail());
    }
  }

  public void signInToGoogle() {
    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);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
      Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
      try {
        // Google Sign In was successful, authenticate with Firebase
        GoogleSignInAccount account = task.getResult(ApiException.class);
        showToastMessage("Google Sign in Succeeded");
        firebaseAuthWithGoogle(account);
      } catch (ApiException e) {
        // Google Sign In failed, update UI appropriately
        Log.w(TAG, "Google sign in failed", e);
        showToastMessage("Google Sign in Failed " + e);
      }
    }
  }

  private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
    firebaseAuth.signInWithCredential(credential)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
              // Sign in success, update UI with the signed-in user's information
              FirebaseUser user = firebaseAuth.getCurrentUser();

              Log.d(TAG, "signInWithCredential:success: currentUser: " + user.getEmail());

              showToastMessage("Firebase Authentication Succeeded ");
              launchMainActivity(user);
            } else {
              // If sign in fails, display a message to the user.

              Log.w(TAG, "signInWithCredential:failure", task.getException());

              showToastMessage("Firebase Authentication failed:" + task.getException());
            }
          }
        });
  }

  private void showToastMessage(String message) {
    Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
  }

  private void launchMainActivity(FirebaseUser user) {
    if (user != null) {
      MainActivity.startActivity(this, user.getDisplayName());
      finish();
    }
  }
}
Open MainActvity layout add logout and revoke access button
<?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/buttonLogout"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginBottom="16dp"
      android:text="@string/logout"
      android:textAllCaps="false"
      app:layout_constraintBottom_toTopOf="@+id/buttonDisconnect"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
  <Button
      android:id="@+id/buttonDisconnect"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/revoke_access"
      android:textAllCaps="false"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />
  <TextView
      android:id="@+id/textViewWelcome"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginBottom="32dp"
      android:text="@string/welcome"
      android:gravity="center"
      app:layout_constraintBottom_toTopOf="@+id/buttonLogout"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
</androidx.constraintlayout.widget.ConstraintLayout>

Go to main activity and add logout code

package com.googlesigninfirebase;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  private static final String TAG = "MainActivity";
  private static final String ARG_NAME = "username";

  public static void startActivity(Context context, String username) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.putExtra(ARG_NAME, username);
    context.startActivity(intent);
  }

  FirebaseAuth firebaseAuth;
  GoogleSignInClient googleSignInClient;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = findViewById(R.id.textViewWelcome);
    if (getIntent().hasExtra(ARG_NAME)) {
      textView.setText(String.format("Welcome - %s", getIntent().getStringExtra(ARG_NAME)));
    }
    findViewById(R.id.buttonLogout).setOnClickListener(this);
    findViewById(R.id.buttonDisconnect).setOnClickListener(this);

    googleSignInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_SIGN_IN);
    firebaseAuth = FirebaseAuth.getInstance();
  }

  @Override
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.buttonLogout:
        signOut();
        break;
      case R.id.buttonDisconnect:
        revokeAccess();
        break;
    }
  }

  private void signOut() {
    // Firebase sign out
    firebaseAuth.signOut();

    // Google sign out
    googleSignInClient.signOut().addOnCompleteListener(this,
        new OnCompleteListener<Void>() {
          @Override
          public void onComplete(@NonNull Task<Void> task) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Signed out of google");
          }
        });
  }

  private void revokeAccess() {
    // Firebase sign out
    firebaseAuth.signOut();

    // Google revoke access
    googleSignInClient.revokeAccess().addOnCompleteListener(this,
        new OnCompleteListener<Void>() {
          @Override
          public void onComplete(@NonNull Task<Void> task) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Revoked Access");
          }
        });
  }
}

Conclusion

With the help of this android app tutorial, We have learned Google Sign In using Firebase android. I hope it’s helpful for you, Help me by sharing this post with all your friends who learning android app development.

Requisition

Please read all Firebase articles in single place.

2 Comments

  1. in this google auth logout function is not working whats the solution for this?

  2. Thanks Morris, out of 4 other tutorials, including the official Android docs, this is the only working example I found.

Write A Comment