Easiest Way to Implement Facebook Login in Android

As an Android developer, we have to add Facebook login in Apps in our routine life. Every time we have to copy-paste code in our Activity class. For that problem, I have written a Facebook Activity class, which you can just copy-paste in your App and extend your Activity class from this FacebookActivity instead of normal Activity. This class will handle Facebook login steps for you. That FacebookLoginActivity is the following.

FacebookLoginActivity.java

Create a class with named FacebookLoginActivity.java and add the following code in that class.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONObject;
import java.util.Arrays;

abstract public class FacebookLoginActivity extends Activity {

    private CallbackManager callbackManager;
    private static int i;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initFacebookLogin();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    void getFacebookInfoInLoginResoponse(LoginResult loginResult) {
        try {
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {

                            if (object == null) {
                                onErrorInFacebookLogin(new Exception());
                                return;
                            }

                            String id = object.optString("id", "");
                            String name = object.optString("name", "");
                            String firstName = object.optString("first_name", "");
                            String lastName = object.optString("last_name", "");
                            String email = object.optString("email", "");

                            onSuccessInFacebookLogin(id, name, firstName, lastName, email);

                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,first_name,last_name,email");
            request.setParameters(parameters);
            request.executeAsync();
        }catch (Exception e){}
    }

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

    public void doFacebookLogin() {
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
    }

    private void initFacebookLogin() {
        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                getFacebookInfoInLoginResoponse(loginResult);
            }

            @Override
            public void onCancel() {
                onCancelFacebookLogin();
            }

            @Override
            public void onError(FacebookException e) {
                onErrorInFacebookLogin(e);
            }
        });

    }

    abstract public void onSuccessInFacebookLogin(String id, String name, String firstName, String lastName, String email);
    abstract public void onErrorInFacebookLogin(Exception exception);
    abstract public void onCancelFacebookLogin();

}

How to Use FacebookLoginActivity class

Now you can extend your Activity class with FacebookLoginActivity class. You also need to override its abstract methods to receive responses. To perform the Facebook login call doFacebookLogin() method. The code is the following.

public class LoginActivity extends FacebookLoginActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    }
    
    public void Click_FBLogin(View v) {
        doFacebookLogin(); // perform facebook login
    }

    // Interface methods
    @Override
    public void onCancelFacebookLogin() {
    }

    @Override
    public void onErrorInFacebookLogin(Exception exception) {
    }

    @Override
    public void onSuccessInFacebookLogin(String id, String name, String firstName, String lastName, String email) {
        // Facebook login is done, do your stuff here
    }
}

Now in the above code, you can see, your Login Activity’s code is short and hides Facebook login implementation details.

Necessary Imports for Facebook Login

Don’t forget to import the Facebook SDK and add the Facebook Activity declaration in Android Manifest.

For that, In your Project level build.gradle add the following jcenter() repository, if it’s not already present.

buildscript { 
repositories {
jcenter()
}}:

In your App level build.gradle add the following dependency

implementation 'com.facebook.android:facebook-login:[5,6)'

Add the following code in the Manifest file under application tag.

<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />

<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />

That’s how to implement Facebook Login in Android in the easiest way. Enjoy 🙂

Don’t forget to visit our Coding Tutorials Library for other coding articles.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: