As an Android programmer, I’ve found it frustrating at times to find help on the web when I need to figure out something that I’ve never done before.  A little while back, Facebook updated their Android SDK to 4.x (as of this writing it is at 4.5.0).  This update made major changes to the way to login to Facebook through your app.  At first, it seems a little overwhelming and complicated, but after a while it actually makes more sense and is easier than past versions.

The problem is, I don’t like to use the Facebook Login button they provide in my apps, because it does not match the theme or style of the apps I make, so I need to use the login manager.

The login manager handles the login sequence to Facebook, asks permissions such as read and publish, and logs out.

The following code examples are not complete 100% apps.  Instead I’ll show the code required to put into your own app.  Also, I use Android Studio for all of my app development, so the examples will be using that with Gradle.

 

First off, in your app module’s build.gradle file, make sure you have mavenCentral() in the repositories section:

repositories {
    mavenCentral() <span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>
}

then under the dependencies section of the same file, add:

dependencies { 
  compile 'com.facebook.android:facebook-android-sdk:4.5.0'
}

*note that this will change depending on the current version of the Facebook Android SDK available.

 

That’s pretty much all that’s needed to install the Facebook SDK to your android project.

Now we’re ready to code.

First, add the following imports at the beginning of your main application or activity class:

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;

Create the following private members in your class declaration:

    private CallbackManager callbackManager;
    private LoginManager loginManager;
    private AccessToken accessToken;

Then, create the following initialization code somewhere in your class:

    public void setUpFacebook()
    {
        // First initialize the Facebook SDK
        FacebookSdk.sdkInitialize(this.getApplicationContext());

        // create the callback manager
        callbackManager = CallbackManager.Factory.create();

        // create the access token
        accessToken = AccessToken.getCurrentAccessToken();

        // create the login manager
        loginManager = LoginManager.getInstance();

        // create the callback for the login manager
        loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
        {
            @Override
            public void onSuccess(LoginResult loginResult)
            {
                // Your app code goes here for when a login is successful.
                // here I update the access token with the login result.
                accessToken.setCurrentAccessToken(loginResult.getAccessToken());
            }

            @Override
            public void onCancel()
            {
                // your app code goes here for when the login is cancelled
                // either by the user or by the Facebook SDK
            }

            @Override
            public void onError(FacebookException exception)
            {
                // your app code goes here for a login exception error
                // such as permissions were denied or another error.
            }
        });
    }

Call your setupFacebook from early in the class, usually at the start of onCreate():

   @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        setupFacebook();

     }

Logging in to Facebook is very simple.  All you need is to call the login manager and get the read permissions.

loginManager.logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends", "email"));

If you need publishing permissions, you can call the following after logging in with read permissions:

loginManager.logInWithPublishPermissions(this, Arrays.asList("publish_actions"));

Logging out is even easier:

loginManager.logOut();

If you need to check if the user is logged in, you can use the following function to make it simple:

    public boolean isConnectedFacebook()
    {

        if (accessToken.getCurrentAccessToken() != null)
        {

            return true;
        }
        else
        {
            return false;
        }

    }

That’s pretty much it!  Logging in to Facebook with the SDK is easier than ever.  In future posts I’ll show how to invite people to your app, and how to set up Facebook for libGDX in Android.