Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Firebase Authentication Tutorial Using Firebase Google Login

Android Firebase Authentication Tutorial Using Firebase Google Login

Hello Developers, Welcome to Android Firebase Authentication Tutorial using Firebase Google Login, Today we will discuss how to enable firebase authentication using the firebase google login.

We have already discussed how to enable Firebase authentication using email and password in our Firebase Getting Started Tutorial

This tutorial is very important as now a days almost all apps have the option for Login with Google and Login with Facebook. This allows users to Sign-In to the app without requiring them to enter any email and password.
Although we have already discussed, how to implement Google Login in android app. Firebase Google Login goes a step forward and makes it very easy to implement Google based authentication.
Additionally, we can make use of all the features offered by Firebase, if we use Firebase Google Login.
In this tutorial, we will create a basic Android Firebase Login app which allows the user to Sign-In using Google and then display their name and email. So let’s get started.


Add Firebase Google Login for Authentication

To add Firebase Google Login follow the below steps :

  1. Go to Firebase Website firebase.google.com and create a firebase account to start with. Go to Firebase console and Create a New Project by clicking on the “Create New Project” Button.
  2. Give the Project name and country you are currently in, Once you are done click on “Create Project” button.
  3. In the next screen choose “Add Firebase to your Android app” and then add the package details and Debug signing certificate SHA-1 key. Please note that adding SHA-1 key is mandatory for implementing google login. If you are not sure how to generate SHA-1 fingerprint see the following tutorial Adding Google Login to Android Apps under the heading Generate SHA-1 fingerprint

  4. This will download the google-services.json file. Download it to your computer. We will add it to our android app later.

  5. In the projects dashboard. Click on Auth Menu, then in the SIGN-IN METHOD click on Google and enable it.

Create Android Firebase Login App

Once you are done with adding , Let’s create the Android Application that will connect to Firebase for user authentication using Firebase Google Login

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter company domain, this is used to uniquely identify your App’s package worldwide. Remember to use the same package name as used in the firebase console.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have used the Activity Name as SignInActivity since this will be the default screen when the user opens the app for the first time.

Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.

Add Permissions and Dependencies

  1. After Gradle syncs the project, add the google-services.json file to your project’s app folder as shown below.
  2. Since we need to connect to the Network add the Internet permission in AndroidManifest.xml file.
  3. AndroidManifest.xml

  4. Now open your project’s build.gradle from the project’s home directory and add the following dependency.
  5. build.gradle

    	classpath 'com.google.gms:google-services:3.0.0'
    
  6. Next, open your app’s build.gradle from the and add the following at the end.
  7. build.gradle

    	apply plugin: 'com.google.gms.google-services'
    
  8. Also add the following dependency in the dependency section.
  9.     compile 'com.google.firebase:firebase-core:9.8.0'
        compile 'com.google.firebase:firebase-auth:9.8.0'
        compile 'com.google.android.gms:play-services-auth:9.8.0'
    

Adding Functionality

Open activity_signin.xml and add the following code. We have two text views, one for displaying the Name and another for dislaying the Email of the Logged in user.
Then we have the custom sign in button by google com.google.android.gms.common.SignInButton, We also have a sign out button to sign out the user.


  • Now open your SignInActivity.java and in the onCreate method, we need to configure Google Sign-In in order to be able to get the user data. So, we create a GoogleSignInOptions object with the requestEmail option.
  •         // Configure Google Sign In
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(getString(R.string.default_web_client_id))
                    .requestEmail()
                    .build();
    
  • Next create a GoogleApiClient object with access to the Google Sign-In API.
  • mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .enableAutoManage(this , new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    
                        }
                    } /* OnConnectionFailedListener */)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .build();
    
  • Next, Add a signIn() method to handle sign-in by creating a sign-in intent with the getSignInIntent() method, and starting the intent with startActivityForResult().
  •    private void signIn() {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
        }
    
  • Next add the onActivityResult() method to retrieve the sign-in result using getSignInResultFromIntent().
  • @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Google Sign In was successful, authenticate with Firebase
                    GoogleSignInAccount account = result.getSignInAccount();
                    firebaseAuthWithGoogle(account);
    
                } else {
                    // Google Sign In failed, update UI appropriately
                    // ...
                }
            }
        }
    

    All the steps above were similar to adding Google Login to android.

  • Add the shared instance of FirebaseAuth object and set up an AuthStateListener that responds to changes in the user’s sign-in state. First declare these.
  •     private FirebaseAuth mAuth;
        private FirebaseAuth.AuthStateListener mAuthListener;
    

    In the onCreate() method add the following AuthStateListener(). When the user is logged in we set make the google signin button invisible and then get the user details from the Firebase User object and display them on the screen.

            mAuth = FirebaseAuth.getInstance();
            mAuthListener = new FirebaseAuth.AuthStateListener() {
                @Override
                public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    FirebaseUser user = firebaseAuth.getCurrentUser();
                    signInButton.setVisibility(View.GONE);
                    signOutButton.setVisibility(View.VISIBLE);
                    if (user != null) {
                        // User is signed in
                        Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                        if(user.getDisplayName() != null)
                            nameTextView.setText("HI " + user.getDisplayName().toString());
                        emailTextView.setText(user.getEmail().toString());
    
                    } else {
                        // User is signed out
                        Log.d(TAG, "onAuthStateChanged:signed_out");
                    }
                    // ...
                }
            };
    
  • Set the onClickListener for the Sign In and Sign Out button. We call the signIn() method when user clicks on the Google Sign In button.

    In the onClickListener() for the Sign Out button we get the FirebaseAuth instance and perform signout from the firebase and also sign out from google account. Additionally resetting the username and email from the screen.

  •             signInButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        signIn();
                    }
                });
                signOutButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FirebaseAuth.getInstance().signOut();
                        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                                new ResultCallback() {
                                    @Override
                                    public void onResult(Status status) {
                                        signInButton.setVisibility(View.VISIBLE);
                                        signOutButton.setVisibility(View.GONE);
                                        emailTextView.setText(" ".toString());
                                        nameTextView.setText(" ".toString());
                                    }
                                });
                    }
                    // ..
                });
    
  • After a user successfully signs in, we have to get an ID token from the GoogleSignInAccount object and exchange it for Firebase credential to authenticate with Firebase. Also add code for handling the AuthStateListener in onStart() and onStop() method.
      @Override
        public void onStart() {
            super.onStart();
            mAuth.addAuthStateListener(mAuthListener);
        }
    
        @Override
        public void onStop() {
            super.onStop();
            if (mAuthListener != null) {
                mAuth.removeAuthStateListener(mAuthListener);
            }
        }
    
        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() {
                        @Override
                        public void onComplete(@NonNull Task task) {
                            Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
    
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Log.w(TAG, "signInWithCredential", task.getException());
                                Toast.makeText(SignInActivity.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    
    

    Here is the complete code for the SignInActivity.java -> SignInActivity.java
    Now, run the app and click on Google Sign In Button to authenticate using Firebase Google Login. It should show a popup with available google account as shown in the demo video. Click on your google account and the Firebase Google Login App should display your Display name and Email Address.


    What’s Next ??

    After the Firebase Google Login Tutorial, Soon We will be covering articles on how to add Facebook Sign-In using Firebase. You can try to add both these login to create a complete login and registration system using firebase.

    Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

    To download the full code for the Firebase Android User Authentication app, Click on the Download Now link below.


    CodeProject

    The post Android Firebase Authentication Tutorial Using Firebase Google Login appeared first on Android Tutorial Point.



  • This post first appeared on Android Tutorial Point, please read the originial post: here

    Share the post

    Android Firebase Authentication Tutorial Using Firebase Google Login

    ×

    Subscribe to Android Tutorial Point

    Get updates delivered right to your inbox!

    Thank you for your subscription

    ×