Industrial Training




Firebase Authentication - Google Login


Firebase Authentication provides backend services for easy use the SDKs and in-built UI libraries to authenticate the user in the application. Most of the apps need the identity of the user, and after knowing their status, the app saves the user's data securely in the cloud. It aims to build a secure authentication system.
Using Firebase Authentication, we will authenticate the log-in of Google, Facebook, GitHub, Twitter and more.
In this tutorial, we will integrate the Firebase Authentication for Google Sign-In functionality in our Android application using Google and Firebase APIs.


Steps to create and configure Android App on Google Firebase Account


  • Create a Firebase developer account at https://firebase.google.com/ and click on 'GO TO CONSOLE'.
  • Click on 'Add project'.
  • Fill the project name and select the analytics location, cloud Firestore location, accept the controller terms and click 'Create project,'.
  • When your new project is successfully ready click on 'Continue'.
  • Select the 'Android' platform SDK.
  • Register your app to Firebase by providing required app information and click on 'Register app'.
    We can get the app certificate SHA-1 key through following steps:

  • Open Android project.
  • Open the Gradle tab from a right side panel.
  • Double click on 'signingReport'.
  • We will found our app SHA-1 key on 'Gradle Console'.
  • 7. Now download the 'google-services.json' file to integrate it into the Android application and click on 'Next'.

    8. Add the firebase SDK dependencies in .gradle files of your application and click 'Sync now' in the IDE and click on 'Next'.


build.gradle (Project)


dependencies {  
    classpath 'com.android.tools.build:gradle:3.0.1'  
    classpath 'com.google.gms:google-services:4.0.1'  
  
    // NOTE: Do not place your application dependencies here; they belong  
    // in the individual module build.gradle files  
}  
dependencies {  
    classpath 'com.android.tools.build:gradle:3.0.1'  
    classpath 'com.google.gms:google-services:4.0.1'  
  
    // NOTE: Do not place your application dependencies here; they belong  
    // in the individual module build.gradle files  
}  

build.gradle (Module)


dependencies {  
    implementation fileTree(dir: 'libs', include: ['*.jar'])  
    implementation 'com.android.support:appcompat-v7:27.1.1'  
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'  
    testImplementation 'junit:junit:4.12'  
    androidTestImplementation 'com.android.support.test:runner:1.0.2'  
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'  
    implementation 'com.google.firebase:firebase-auth:16.0.3'  
    implementation 'com.google.firebase:firebase-core:16.0.3'  
    implementation 'com.google.android.gms:play-services-auth:16.0.0'  
    implementation 'com.github.bumptech.glide:glide:3.7.0'  
}  
apply plugin: 'com.google.gms.google-services'  
dependencies {  
    implementation fileTree(dir: 'libs', include: ['*.jar'])  
    implementation 'com.android.support:appcompat-v7:27.1.1'  
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'  
    testImplementation 'junit:junit:4.12'  
    androidTestImplementation 'com.android.support.test:runner:1.0.2'  
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'  
    implementation 'com.google.firebase:firebase-auth:16.0.3'  
    implementation 'com.google.firebase:firebase-core:16.0.3'  
    implementation 'com.google.android.gms:play-services-auth:16.0.0'  
    implementation 'com.github.bumptech.glide:glide:3.7.0'  
}  
apply plugin: 'com.google.gms.google-services' 

AndroidManifest.xml


Add the Internet permission in the AndroidManifest.xml file to access the network connection.


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

9. Run your app to verify the installation configuration, if everything is fine it displays a success message and then click on 'Continue to console'.

10. At console page select Authentication -> Sign-in method ->Google -> Enable and click on 'Save'.


Android Firebase Authentication with Google Sign-In Example


In this example, we will integrate the Firebase Authentication with Google Sign-In in our Android app. Once the user successfully login through Google Sign-In, we will authenticate them with Firebase Authentication and then redirect the user to the next activity (ProfileActivity) and display their detail.
We need to paste the downloaded 'google-services.json' file in our Android project app directory.


activity_main.xml


Add the following code in an activity_main.xml file. In this activity, we implement the custom Google Sign-in button.


< ?xml version="1.0" encoding="utf-8"?>  
< RelativeLayout 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="example.javatpoint.com.firebasegooglelogin.MainActivity">  
  
    < TextView  
        android:id="@+id/textView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_marginLeft="20dp"  
        android:layout_marginRight="20dp"  
        android:textSize="20dp"  
        android:text="This is main activity, sign in to move next activity." />  
  
    < com.google.android.gms.common.SignInButton  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/sign_in_button"  
        android:layout_marginLeft="20dp"  
        android:layout_marginRight="20dp"  
        android:layout_alignParentBottom="true"  
        android:layout_marginBottom="20dp">  
  
    < /com.google.android.gms.common.SignInButton>  
  
  
< /RelativeLayout>  
< ?xml version="1.0" encoding="utf-8"?>  
< RelativeLayout 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="example.javatpoint.com.firebasegooglelogin.MainActivity">  
  
    < TextView  
        android:id="@+id/textView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_marginLeft="20dp"  
        android:layout_marginRight="20dp"  
        android:textSize="20dp"  
        android:text="This is main activity, sign in to move next activity." />  
  
    < com.google.android.gms.common.SignInButton  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/sign_in_button"  
        android:layout_marginLeft="20dp"  
        android:layout_marginRight="20dp"  
        android:layout_alignParentBottom="true"  
        android:layout_marginBottom="20dp">  
  
    < /com.google.android.gms.common.SignInButton>  
  
  
< /RelativeLayout>  

strings.xml


Add your web client id in the string.xml file. Even you can use the default Google web client id in the program.


< resources>  
    < string name="app_name">Firebase Google Login< /string>  
    < string name="web_client_id">xxxxxxxx..place your web client id here< /string>  
< /resources>  
< resources>  
    < string name="app_name">Firebase Google Login< /string>  
    < string name="web_client_id">xxxxxxxx..place your web client id here< /string>  
< /resources>  

MainActivity.java


Add the following code in MainActivity.java class. The functionality of classes and methods used in MainActivity.java class are given below:


  • The new FirebaseAuth.AuthStateListener(){} is used as an authentication listener to check whether the user is sign-in or not. If the users successfully sign-in we place other firebase logic.
  • The new GoogleSignInOptions.Builder() method configure the Google Sign-in to get the user data using the requestEmail option.
  • Clicking on Sign-In button, it calls Auth.GoogleSignInApi.getSignInIntent(googleApiClient) and starting the intent with startActivityForResult().
  • The onActivityResult() we get the result of Google Sign-in request.
  • If handleSignInResult(result) returns true, we get the Google Authentication using idToken.
  • Calling firebaseAuthWithGoogle(credential) for making Firebase Authentication with Google.

If the Firebase authentication is success, we redirect the user to the next activity (ProfileActivity.java)


package example.javatpoint.com.firebasegooglelogin;  
  
import android.content.Intent;  
import android.support.annotation.NonNull;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.util.Log;  
import android.view.View;  
import android.widget.Toast;  
  
import com.google.android.gms.auth.api.Auth;  
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;  
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;  
import com.google.android.gms.auth.api.signin.GoogleSignInResult;  
import com.google.android.gms.common.ConnectionResult;  
import com.google.android.gms.common.SignInButton;  
import com.google.android.gms.common.api.GoogleApiClient;  
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 MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {  
  
    private static final String TAG = "MainActivity";  
    private SignInButton signInButton;  
    private GoogleApiClient googleApiClient;  
    private static final int RC_SIGN_IN = 1;  
    String name, email;  
    String idToken;  
    private FirebaseAuth firebaseAuth;  
    private FirebaseAuth.AuthStateListener authStateListener;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();  
        //this is where we start the Auth state Listener to listen for whether the user is signed in or not  
        authStateListener = new FirebaseAuth.AuthStateListener(){  
            @Override  
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {  
                // Get signedIn user  
                FirebaseUser user = firebaseAuth.getCurrentUser();  
  
                //if user is signed in, we call a helper method to save the user details to Firebase  
                if (user != null) {  
                    // User is signed in  
                    // you could place other firebase code  
                    //logic to save the user details to Firebase  
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());  
                } else {  
                    // User is signed out  
                    Log.d(TAG, "onAuthStateChanged:signed_out");  
                }  
            }  
        };  
  
        GoogleSignInOptions gso =  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
                .requestIdToken(getString(R.string.web_client_id))//you can also use R.string.default_web_client_id  
                .requestEmail()  
                .build();  
        googleApiClient=new GoogleApiClient.Builder(this)  
                .enableAutoManage(this,this)  
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)  
                .build();  
  
        signInButton = findViewById(R.id.sign_in_button);  
        signInButton.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);  
                startActivityForResult(intent,RC_SIGN_IN);  
            }  
        });  
    }  
  
    @Override  
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
  
    }  
  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        super.onActivityResult(requestCode, resultCode, data);  
        if(requestCode==RC_SIGN_IN){  
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);  
            handleSignInResult(result);  
        }  
    }  
  
    private void handleSignInResult(GoogleSignInResult result){  
        if(result.isSuccess()){  
            GoogleSignInAccount account = result.getSignInAccount();  
            idToken = account.getIdToken();  
            name = account.getDisplayName();  
            email = account.getEmail();  
            // you can store user data to SharedPreference  
            AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);  
            firebaseAuthWithGoogle(credential);   
        }else{  
            // Google Sign In failed, update UI appropriately  
            Log.e(TAG, "Login Unsuccessful. "+result);  
            Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_SHORT).show();  
        }  
    }  
    private void firebaseAuthWithGoogle(AuthCredential credential){  
  
        firebaseAuth.signInWithCredential(credential)  
                .addOnCompleteListener(this, new OnCompleteListener< AuthResult>() {  
                    @Override  
                    public void onComplete(@NonNull Task< AuthResult> task) {  
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());  
                        if(task.isSuccessful()){  
                            Toast.makeText(MainActivity.this, "Login successful", Toast.LENGTH_SHORT).show();  
                            gotoProfile();  
                        }else{  
                            Log.w(TAG, "signInWithCredential" + task.getException().getMessage());  
                            task.getException().printStackTrace();  
                            Toast.makeText(MainActivity.this, "Authentication failed.",  
                                    Toast.LENGTH_SHORT).show();  
                        }  
  
                    }  
                });  
    }  
  
  
  
  
    private void gotoProfile(){  
        Intent intent = new Intent(MainActivity.this, ProfileActivity.class);  
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);  
        startActivity(intent);  
        finish();  
    }  
    @Override  
    protected void onStart() {  
        super.onStart();  
        if (authStateListener != null){  
            FirebaseAuth.getInstance().signOut();  
        }  
        firebaseAuth.addAuthStateListener(authStateListener);  
    }  
  
    @Override  
    protected void onStop() {  
        super.onStop();  
        if (authStateListener != null){  
            firebaseAuth.removeAuthStateListener(authStateListener);  
        }  
    }  
  
}  
package example.javatpoint.com.firebasegooglelogin;  
  
import android.content.Intent;  
import android.support.annotation.NonNull;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.util.Log;  
import android.view.View;  
import android.widget.Toast;  
  
import com.google.android.gms.auth.api.Auth;  
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;  
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;  
import com.google.android.gms.auth.api.signin.GoogleSignInResult;  
import com.google.android.gms.common.ConnectionResult;  
import com.google.android.gms.common.SignInButton;  
import com.google.android.gms.common.api.GoogleApiClient;  
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 MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {  
  
    private static final String TAG = "MainActivity";  
    private SignInButton signInButton;  
    private GoogleApiClient googleApiClient;  
    private static final int RC_SIGN_IN = 1;  
    String name, email;  
    String idToken;  
    private FirebaseAuth firebaseAuth;  
    private FirebaseAuth.AuthStateListener authStateListener;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();  
        //this is where we start the Auth state Listener to listen for whether the user is signed in or not  
        authStateListener = new FirebaseAuth.AuthStateListener(){  
            @Override  
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {  
                // Get signedIn user  
                FirebaseUser user = firebaseAuth.getCurrentUser();  
  
                //if user is signed in, we call a helper method to save the user details to Firebase  
                if (user != null) {  
                    // User is signed in  
                    // you could place other firebase code  
                    //logic to save the user details to Firebase  
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());  
                } else {  
                    // User is signed out  
                    Log.d(TAG, "onAuthStateChanged:signed_out");  
                }  
            }  
        };  
  
        GoogleSignInOptions gso =  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
                .requestIdToken(getString(R.string.web_client_id))//you can also use R.string.default_web_client_id  
                .requestEmail()  
                .build();  
        googleApiClient=new GoogleApiClient.Builder(this)  
                .enableAutoManage(this,this)  
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)  
                .build();  
  
        signInButton = findViewById(R.id.sign_in_button);  
        signInButton.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);  
                startActivityForResult(intent,RC_SIGN_IN);  
            }  
        });  
    }  
  
    @Override  
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
  
    }  
  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        super.onActivityResult(requestCode, resultCode, data);  
        if(requestCode==RC_SIGN_IN){  
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);  
            handleSignInResult(result);  
        }  
    }  
  
    private void handleSignInResult(GoogleSignInResult result){  
        if(result.isSuccess()){  
            GoogleSignInAccount account = result.getSignInAccount();  
            idToken = account.getIdToken();  
            name = account.getDisplayName();  
            email = account.getEmail();  
            // you can store user data to SharedPreference  
            AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);  
            firebaseAuthWithGoogle(credential);   
        }else{  
            // Google Sign In failed, update UI appropriately  
            Log.e(TAG, "Login Unsuccessful. "+result);  
            Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_SHORT).show();  
        }  
    }  
    private void firebaseAuthWithGoogle(AuthCredential credential){  
  
        firebaseAuth.signInWithCredential(credential)  
                .addOnCompleteListener(this, new OnCompleteListener< AuthResult>() {  
                    @Override  
                    public void onComplete(@NonNull Task< AuthResult> task) {  
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());  
                        if(task.isSuccessful()){  
                            Toast.makeText(MainActivity.this, "Login successful", Toast.LENGTH_SHORT).show();  
                            gotoProfile();  
                        }else{  
                            Log.w(TAG, "signInWithCredential" + task.getException().getMessage());  
                            task.getException().printStackTrace();  
                            Toast.makeText(MainActivity.this, "Authentication failed.",  
                                    Toast.LENGTH_SHORT).show();  
                        }  
  
                    }  
                });  
    }  
  
  
  
  
    private void gotoProfile(){  
        Intent intent = new Intent(MainActivity.this, ProfileActivity.class);  
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);  
        startActivity(intent);  
        finish();  
    }  
    @Override  
    protected void onStart() {  
        super.onStart();  
        if (authStateListener != null){  
            FirebaseAuth.getInstance().signOut();  
        }  
        firebaseAuth.addAuthStateListener(authStateListener);  
    }  
  
    @Override  
    protected void onStop() {  
        super.onStop();  
        if (authStateListener != null){  
            firebaseAuth.removeAuthStateListener(authStateListener);  
        }  
    }  
  
}  

profile_activity.xml


Add the following code in the profile_activity.xml file. The ImageView is used for display the user profile image, TextView is for name, email id, and a button for log-out.

<
< ?xml version="1.0" encoding="utf-8"?>  
< RelativeLayout 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="example.javatpoint.com.firebasegooglelogin.ProfileActivity">  
  
   
        < LinearLayout  
            android:layout_width="match_parent"  
            android:layout_height="match_parent"  
            android:gravity="center"  
            android:orientation="vertical">  
            < ImageView  
                android:layout_width="80dp"  
                android:layout_height="80dp"  
                android:id="@+id/profileImage"  
                />  
            < TextView  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/name"  
                android:text="name"  
                android:textSize="20dp"  
                android:layout_marginTop="20dp"/>  
            < TextView  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/email"  
                android:textSize="20dp"  
                android:text="email"  
                android:layout_marginTop="20dp"/>  
            < TextView  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/userId"  
                android:textSize="20dp"  
                android:text="id"  
                android:layout_marginTop="20dp"/>  
            < Button  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/logoutBtn"  
                android:text="Logout"  
                android:layout_marginTop="30dp"/>  
        < /LinearLayout>  
< /RelativeLayout>  
< ?xml version="1.0" encoding="utf-8"?>  
< RelativeLayout 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="example.javatpoint.com.firebasegooglelogin.ProfileActivity">  
  
  
        < LinearLayout  
            android:layout_width="match_parent"  
            android:layout_height="match_parent"  
            android:gravity="center"  
            android:orientation="vertical">  
            < ImageView  
                android:layout_width="80dp"  
                android:layout_height="80dp"  
                android:id="@+id/profileImage"  
                />  
            < TextView  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/name"  
                android:text="name"  
                android:textSize="20dp"  
                android:layout_marginTop="20dp"/>  
            < TextView  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/email"  
                android:textSize="20dp"  
                android:text="email"  
                android:layout_marginTop="20dp"/>  
            < TextView  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/userId"  
                android:textSize="20dp"  
                android:text="id"  
                android:layout_marginTop="20dp"/>  
            < Button  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:id="@+id/logoutBtn"  
                android:text="Logout"  
                android:layout_marginTop="30dp"/>  
        < /LinearLayout>  
< /RelativeLayout>  

ProfileActivity.java

In this ProfileActivity.java class, we get the user information and display them. The GoogleSignInResult class implements the Result interface which represents the final result of invoking an API method of Google Play Services.
The GoogleSignInAccount class keeps the necessary information of the user.


package example.javatpoint.com.firebasegooglelogin;  
  
import android.content.Intent;  
import android.support.annotation.NonNull;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
import android.widget.ImageView;  
import android.widget.TextView;  
import android.widget.Toast;  
  
import com.bumptech.glide.Glide;  
import com.google.android.gms.auth.api.Auth;  
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;  
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;  
import com.google.android.gms.auth.api.signin.GoogleSignInResult;  
import com.google.android.gms.common.ConnectionResult;  
import com.google.android.gms.common.api.GoogleApiClient;  
import com.google.android.gms.common.api.OptionalPendingResult;  
import com.google.android.gms.common.api.ResultCallback;  
import com.google.android.gms.common.api.Status;  
import com.google.firebase.auth.FirebaseAuth;  
  
public class ProfileActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {  
    Button logoutBtn;  
    TextView userName,userEmail,userId;  
    ImageView profileImage;  
    private GoogleApiClient googleApiClient;  
    private GoogleSignInOptions gso;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_profile);  
  
        logoutBtn = findViewById(R.id.logoutBtn);  
        userName = findViewById(R.id.name);  
        userEmail = findViewById(R.id.email);  
        userId = findViewById(R.id.userId);  
        profileImage = findViewById(R.id.profileImage);  
  
        gso =  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
                .requestEmail()  
                .build();  
  
        googleApiClient=new GoogleApiClient.Builder(this)  
                .enableAutoManage(this,this)  
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)  
                .build();  
  
  
        logoutBtn.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                FirebaseAuth.getInstance().signOut();  
                Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(  
                        new ResultCallback< Status>() {  
                            @Override  
                            public void onResult(Status status) {  
                                if (status.isSuccess()){  
                                    gotoMainActivity();  
                                }else{  
                                    Toast.makeText(getApplicationContext(),"Session not close",Toast.LENGTH_LONG).show();  
                                }  
                            }  
                        });  
            }  
        });  
    }  
  
    @Override  
    protected void onStart() {  
        super.onStart();  
        OptionalPendingResult< GoogleSignInResult> opr= Auth.GoogleSignInApi.silentSignIn(googleApiClient);  
        if(opr.isDone()){  
            GoogleSignInResult result=opr.get();  
            handleSignInResult(result);  
        }else{  
            opr.setResultCallback(new ResultCallback< GoogleSignInResult>() {  
                @Override  
                public void onResult(@NonNull GoogleSignInResult googleSignInResult) {  
                    handleSignInResult(googleSignInResult);  
                }  
            });  
        }  
    }  
    private void handleSignInResult(GoogleSignInResult result){  
        if(result.isSuccess()){  
            GoogleSignInAccount account=result.getSignInAccount();  
            userName.setText(account.getDisplayName());  
            userEmail.setText(account.getEmail());  
            userId.setText(account.getId());  
            try{  
                Glide.with(this).load(account.getPhotoUrl()).into(profileImage);  
            }catch (NullPointerException e){  
                Toast.makeText(getApplicationContext(),"image not found",Toast.LENGTH_LONG).show();  
            }  
  
        }else{  
            gotoMainActivity();  
        }  
    }  
    private void gotoMainActivity(){  
        Intent intent=new Intent(this,MainActivity.class);  
        startActivity(intent);  
    }  
    @Override  
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
  
    }  
}  
package example.javatpoint.com.firebasegooglelogin;  
  
import android.content.Intent;  
import android.support.annotation.NonNull;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
import android.widget.ImageView;  
import android.widget.TextView;  
import android.widget.Toast;  
  
import com.bumptech.glide.Glide;  
import com.google.android.gms.auth.api.Auth;  
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;  
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;  
import com.google.android.gms.auth.api.signin.GoogleSignInResult;  
import com.google.android.gms.common.ConnectionResult;  
import com.google.android.gms.common.api.GoogleApiClient;  
import com.google.android.gms.common.api.OptionalPendingResult;  
import com.google.android.gms.common.api.ResultCallback;  
import com.google.android.gms.common.api.Status;  
import com.google.firebase.auth.FirebaseAuth;  
  
public class ProfileActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {  
    Button logoutBtn;  
    TextView userName,userEmail,userId;  
    ImageView profileImage;  
    private GoogleApiClient googleApiClient;  
    private GoogleSignInOptions gso;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_profile);  
  
        logoutBtn = findViewById(R.id.logoutBtn);  
        userName = findViewById(R.id.name);  
        userEmail = findViewById(R.id.email);  
        userId = findViewById(R.id.userId);  
        profileImage = findViewById(R.id.profileImage);  
  
        gso =  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
                .requestEmail()  
                .build();  
  
        googleApiClient=new GoogleApiClient.Builder(this)  
                .enableAutoManage(this,this)  
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)  
                .build();  
  
  
        logoutBtn.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                FirebaseAuth.getInstance().signOut();  
                Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(  
                        new ResultCallback< Status>() {  
                            @Override  
                            public void onResult(Status status) {  
                                if (status.isSuccess()){  
                                    gotoMainActivity();  
                                }else{  
                                    Toast.makeText(getApplicationContext(),"Session not close",Toast.LENGTH_LONG).show();  
                                }  
                            }  
                        });  
            }  
        });  
    }  
  
    @Override  
    protected void onStart() {  
        super.onStart();  
        OptionalPendingResult< GoogleSignInResult> opr= Auth.GoogleSignInApi.silentSignIn(googleApiClient);  
        if(opr.isDone()){  
            GoogleSignInResult result=opr.get();  
            handleSignInResult(result);  
        }else{  
            opr.setResultCallback(new ResultCallback< GoogleSignInResult>() {  
                @Override  
                public void onResult(@NonNull GoogleSignInResult googleSignInResult) {  
                    handleSignInResult(googleSignInResult);  
                }  
            });  
        }  
    }  
    private void handleSignInResult(GoogleSignInResult result){  
        if(result.isSuccess()){  
            GoogleSignInAccount account=result.getSignInAccount();  
            userName.setText(account.getDisplayName());  
            userEmail.setText(account.getEmail());  
            userId.setText(account.getId());  
            try{  
                Glide.with(this).load(account.getPhotoUrl()).into(profileImage);  
            }catch (NullPointerException e){  
                Toast.makeText(getApplicationContext(),"image not found",Toast.LENGTH_LONG).show();  
            }  
  
        }else{  
            gotoMainActivity();  
        }  
    }  
    private void gotoMainActivity(){  
        Intent intent=new Intent(this,MainActivity.class);  
        startActivity(intent);  
    }  
    @Override  
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
  
    }  
}  

Output:




Hi I am Pluto.