Firebase: Google Sign-In

Rahul Lad
Rahul Lad
Sep 1, 2018 · 5 min read

Hello friends, a beginner level android developer usually struggles to interpret documentation provided by google, they are very short and without any suitable example. So, here I am to help you out.

Today, we will be doing a simple android app with Google Sign-In option. I have extracted few important details from documentation and presented in simpler way. So, without wasting any time Lets begin!

I have divided this tutorial in three parts:

Part A: Create an Android app in Android Studio.

Step 1: Launch Android Studio and Go to File → New → New Project and enter your Application Name. We will need to mention your package name while registering your app to Firebase. It requires Android version 4.0 (Ice Cream Sandwich) or newer. Make sure you use the latest one.

Step 2: Add dependencies and permissions.

In your project level build.gradle file, add following dependency

classpath 'com.google.gms:google-services:4.0.0'

In your app-level build.gradle file, add following dependency

implementation 'com.google.firebase:firebase-auth:11.6.0'
implementation 'com.google.android.gms:play-services-auth:11.6.0'

At the bottom of the app-level build.gradle file, add following code

apply plugin: 'com.google.gms.google-services'

Now, in AndroidManifest.xml file add following permission

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

If you Sync at this point it will throw error saying “File google-services.json is missing”. Wait for the next step to complete.

Part B: Firebase Console (Registering your app on Firebase)

Step 1: Open Firebase website, if you are not logged in then please login using your google account. After logged in click on GO TO CONSOLE. Then click on Add Project. It will open a popup window which will look like this.

You can write any name(need not to be same as of your android project name). Select your country, accept terms and hit Create Project button.

Now click on Add Firebase to your Android App

Then below screen will come, you have to enter package name and nickname for your app.

Hit Register app button.

Now download the google-service.json file and paste in your app folder.

Click Next ->It will ask to add dependencies that we have added already, so again click next.

After adding google-service.json file in app folder you can click Sync button (or rebuild your project)in your android studio. Now error will be gone and your app will install.

In step 4 of their documentation they will ask to run your app, right now a progress wheel will rotate, actually is waiting to your to communicate to your Firebase. So Install your app. After successful communication it will look like this.

Now go to console and click on Authentication from left pan -> click on sign-in method. There you will see google option. Edit it and make it enable and Save.

Hurrah!! There you go. Your app is ready for Firebase.

Part C: Coding part

Now we have to write down bunch of code.

MainActivity is my landing page and LoginSuccessActivity opens after successful login.

public class MainActivity extends AppCompatActivity {

private static final String TAG = "LOGIN";
private static final int RC_SIGN_IN = 100;
private SignInButton signIn;
GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;

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

signIn = findViewById(R.id.sign_in_button);

mAuth = FirebaseAuth.getInstance();

signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});

// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();

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

}

private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}

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

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);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Toast.makeText(getApplicationContext(), "Authentication went wrong!! ERROR", Toast.LENGTH_SHORT).show();
}
}
}

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

AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Login SUCCESS", Toast.LENGTH_SHORT).show();
// FirebaseUser user = mAuth.getCurrentUser();
goToSuccessActivity();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(getApplicationContext(), "Login FAILED!!!!", Toast.LENGTH_SHORT).show();
}
}
});
}

private void goToSuccessActivity() {
Intent intent = new Intent(MainActivity.this, LoginSuccessActivity.class);
startActivity(intent);
}

@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (null != currentUser) {
goToSuccessActivity();
}
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>

</android.support.constraint.ConstraintLayout>

After successful login it will redirect to LoginSuccessActivity. This activity gives functionality to logout user from your app. Also if user is logged in then it will skip MainActivity and will open this.

To Sign Out from app : FirebaseAuth.getInstance().signOut();

public class LoginSuccessActivity extends AppCompatActivity {
Button logout;
TextView name;
private FirebaseAuth mAuth;

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

name = findViewById(R.id.name);
logout = findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signOut();
}
});
mAuth = FirebaseAuth.getInstance();
}

private void signOut() {
FirebaseAuth.getInstance().signOut();
finish();
}

@Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (null != user){
name.setText(user.getDisplayName());
}
}

@Override
public void onBackPressed() {
finishAffinity();
}
}

Code Reference: https://github.com/ladrahul25/GoogleSignIn

That’s Done!! Enjoy Firebasing.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade