Introduction to Facebook APIs


To follow along with this article, you need the following skills and tools:

  • Basic knowledge of Java™ technology and how to use Eclipse (or your favorite IDE)
  • Java Development Kit (version 5 or 6 required)
  • Eclipse (version 3.4 or 3.5)
  • Android SDK and ADT plug-in

For download and setup information, see Related links.

Overview of the Facebook Platform APIs

Before covering the Facebook SDK for Android, it is important to understand the Facebook Platform and its APIs. According to Facebook, the Facebook Platform allows anyone to “build social applications on Facebook and the Web.” To enable you to build such applications, Facebook offers an extensive collection of core and advanced APIs and SDKs (see Related links).

The core Facebook Platform API is the Graph API that allows you to read and write data to and from Facebook. Facebook also has what is called the Old Rest API. The newer Graph API changes the API paradigm from a method-oriented way of reading and writing data to and from Facebook to a new way that uses objects (think user profiles, friends, posts, photos, likes, and so on) and their relationships or connections with each other. This approach simplifies the Facebook API and makes it more consistent when working with objects. Note that while the Graph API is the preferred Facebook API, the Old REST API is still active and supported. Both the Graph and the REST APIs are applicable to mobile applications, both native and mobile web applications, including mobile web content within native applications through the use of WebViews.

Graph API objects are assigned a unique ID and are easily addressable using a URL that can be further qualified to address a specific object/connection. The general structure of an object URL is as follows: where OBJECT_ID is the object’s unique ID and CONNECTION_TYPE is one of the connection types supported by the object. For example, a page supports the following connections: feed/wall, photos, notes, posts, members, and so on.

With the Graph API, you can retrieve an object, delete an object, and publish objects. You can search, update objects, filter results, and even dynamically discover the connections/relationships of an object.

By default, applications have access to the user’s public data. To access private data, applications must first request the user’s permissions, which are called extended permissions. Facebook defines a large number of permissions that you can read at the Extended Permissions page (see Related links).

Introduction to the Facebook SDK for Android

Now that you have a better understanding of the Facebook Platform APIs, look at the Facebook SDK for Android.

The Facebook SDK for Android is a Java programming language wrapper to the Facebook Graph and old REST APIs. This SDK is open source, and it is hosted at github’s facebook / facebook-android-sdk repository (see Related links). Note that due to the evolving nature of the open-source SDK, expect future changes to the SDK. The SDK is licensed under the Apache License, Version 2.0.

The Facebook SDK for Android hides a lot of the details covered in the previous section, Overview of the Facebook Platform APIs. It does so by providing six Java classes.

Classes Description
AsyncFacebookRunner A helper class that implements asynchronous Facebook API calls
DialogError A class that encapsulates dialog error
Facebook Main Facebook class for interaction with the Facebook Platform APIs
FacebookError A class that encapsulates a Facebook error
FbDialog A class that implements a WebView for Facebook dialogs
Util A helper class with a number of utility methods

The Facebook SDK for Android also brings a couple of useful examples that you can use as a baseline for your own applications.

Of special interest are the core Facebook class and the Facebook Dialog class, which I cover in more detail next. The core Facebook class encapsulates methods to authorize the user, create Facebook dialogs, make API requests, log out the user, and get or set access and session information and status. The Facebook Dialog class implements a WebView and methods for its creation as well as the logic for handling Facebook URL (status) responses. The dialog is central to the way the SDK operates. The SDK provides two methods to authenticate, one that is referred to as single-sign on which uses, if installed, the native Facebook application dialogs, and the default WebView approach to dialogs. In this article, I will focus on the WebView approach. The rest of the SDK classes are helper classes used to encapsulate error information or provide useful utilities used throughout the SDK.

The following sections focus on use-cases for a typical Facebook application:

  • Installing the Facebook SDK for Android
  • Registering your application
  • Creating the SampleApp
  • Displaying Facebook dialogs
  • Authorizing the user
  • Making API requests

Installing the Android SDK

You have to download and install Eclipse or your favorite IDE. In addition, you must install the Android SDK. For information on how to download and install Eclipse and the Android SDK, see the Download the Android SDK page at the Android Developer web site (see Related links).

Installing the Facebook SDK for Android

The Facebook SDK for Android is hosted at github’s facebook / facebook-android-sdk repository. Download the SDK source, and extract it into your working directory. Start Eclipse, and create an Android Project by selecting File Menu -> New -> Project and choose the Android Project. Create the project from the existing source and point to the extracted source directory (see Download) for the source code).

Registering your application

Before you start, you have to register your Facebook application and get an application ID (client_id) and associated secret key (client_secret). The client ID is used in your application when making the different Facebook API calls.

The sample application

The sample application, which for simplicity sake I call SampleApp, shows you how to use the Facebook SDK for Android. The application consists of a single file that implements the SampleApp activity and that uses one screen to display messages, the list of Facebook friends and menu items to login/authenticate the user, get a list of friends, and post to the authenticated user’s (me) wall.

Before you start, remember that you must register your application with Facebook, as previously explained, and that you have to set the attribute APP_ID in to the client_id as provided by Facebook (see Initializing the application ID).

Initializing the application ID
// Set application ID to your registered app client_id
// See
public static final String APP_ID = ".....";

For the Sample Application screen, use a linear layout that contains a TextView for simple status messages, a ListView to display the list of Facebook friends retrieved from the server, and menu items to logic/authenticate the user, get a list of friends, and post to the authenticated user’s (me) wall. Main screen UI declarations shows the XML UI declarations for the main UI screen layout.

Main screen UI declarations
<?xml version="1.0" encoding="utf-8"?>

    <TextView android:id="@+id/txt"

        android:text="No data"

ListView row UI declarations shows the XML UI declarations for each row in your ListView.

ListView row UI declarations
<?xml version="1.0" encoding="utf-8"?>

And Menu items UI declarations shows the XML UI declarations for the menu items.

<menu xmlns:android="">
    <item android:id="@+id/login" android:title="Login"/>
    <item android:id="@+id/getfriends" android:title="Get Friends"/>
    <item android:id="@+id/wallpost" android:title="Wall Post" />

SampleApp screen layout shows the results of the XML UI declaration for SampleApp before (with the Login button) and after login (with the Logout, Get Friends, and Wall Post buttons).

SampleApp screen layout

Screen capture of the pre-login and post-login screen layouts in the SampleApp

The SampleApp onCreate() method is invoked by the Android platform when the SampleApp instance is created. This method performs a basic check to make sure that the App ID is set before proceeding, initializes the UI resources, and initializes the Facebook session instance (see Initializing the application).

Initializing the application
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {

    // Make sure the app client_app has been set
    if (APP_ID == null) {
        "Warning", "Facebook Application ID must be set...");

    // Initialize the content view
    // Get the status text line resource
    mText = (TextView) SampleApp.this.findViewById(;

    // Setup the ListView Adapter that is loaded when selecting "get friends"
    listView = (ListView) findViewById(;
    friendsArrayAdapter = new FriendsArrayAdapter(this, R.layout.rowlayout, friends);

    // Define a spinner used when loading the friends over the network
    mSpinner = new ProgressDialog(listView.getContext());

    // Initialize the Facebook session
    mFacebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(mFacebook);


The rest of the application flow is triggered by UI interactions through the menu items. Three menu items are defined 1) login/logout (toggle), 2) get friends, and 3) post to the wall, as illustrated in Menu items UI declarations. As the user selects a menu item, the application performs the appropriate action. The following listing shows how the menu items are handled. Creating the menu shows how to instantiate the menu by deflating its XML definition.

Creating the menu
 * Invoked at the time to create the menu
 * @param the menu to create
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(, menu);
    return true;

Creating the menu shows how the menu items are modified before getting displayed, that is, show the proper “login” or “logout” state and enable/disable “get friends” and “post to wall” as appropriate.

Creating the menu
 * Invoked when preparing to display the menu
 * @param menu is the menu to prepare
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem loginItem = menu.findItem(;
    MenuItem postItem = menu.findItem(;
    MenuItem getfriendsItem = menu.findItem(;
    if (mFacebook.isSessionValid()) {
    } else {
    return super.onPrepareOptionsMenu(menu);

Handling the menu selection shows how the menu items are handled and the appropriate action (login/logout, get friends, post to wall) invoked.

Handling the menu selection
 * Invoked when a menu item has been selected
 * @param item is the selected menu item
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        // Login/logout toggle
            // Toggle the button state.
            //  If coming from login transition to logout.
            if (mFacebook.isSessionValid()) {
                AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
                asyncRunner.logout(this.getBaseContext(), new LogoutRequestListener());
            } else {
                // Toggle the button state.
                //  If coming from logout transition to login (authorize).
                mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());

        // Wall Post
        case // Wall Post
            mFacebook.dialog(SampleApp.this, "stream.publish", new

        // Get Friend's List
        case // Wall Post
            // Get the authenticated user's friends
            mAsyncRunner.request("me/friends", new FriendsRequestListener());

            return false;

    return true;

The application uses a number of callbacks to handle the state of each asynchronous call. The SampleApp defines a callback to handle the success or failure for login requests, for logout dialogs, for post to wall dialogs and for get friends requests. You can take this sample application and add your own actions by just following the same pattern of adding menus and the corresponding calls to Facebook with the corresponding callbacks to receive state messages.

Both the login and “post to wall” menu items invoke the Facebook dialog which by default uses the SDK WebView-based dialogs if the single-sign on option is not defined; this is explained in the following section.

The FriendsRequestListener callback is covered in Making Facebook API Requests. The last callback, MyDialogListener implements the Facebook SDK for Android DialogListener, which is used for Facebook requests that uses the SDK WebView-based dialogs, as explained in the following section. The implementer of DialogListener must implement the appropriate completion logic; for example, this is used during login and wall post requests.

Displaying Facebook dialogs

The Facebook SDK for Android relies on Facebook web/server-based dialogs for user interactions such as user authorization, permissions, and message publishing. The core SDK class defines the method dialog() when it generates the UI dialog for the request action (see The Facebook Dialog method).

The Facebook Dialog method
 * Generate a UI dialog for the request action in the given Android context
 * with the provided parameters.
public void dialog(
        Context context,
        String action,
        Bundle parameters,
        final DialogListener listener) {

This asynchronous method takes for input the application context, the action to perform (such as login, publish_stream, read_stream, offline_access), the required parameters for the specific request or action, and a listener method that is called when the asynchronous methods complete executing. The method creates the appropriate WebView dialog. For example, to publish a status message, you make a call to the core Facebook class method dialog() passing the action stream.publish (see Calling the dialog() method and processing the callback).

Calling the dialog method and processing the callback


mFacebook = new Facebook(); // Facebook core

// Create a Facebook dialog (using the call asynchronous API)
    new MyDialogListener());


// My asynchronous dialog listener
public class MyDialogListener extends {

    public void onComplete(Bundle values) {

        final String postId = values.getString("post_id");

        if (postId != null) {

            // "Wall post made..."

        } else {
            // "No wall post made..."


    public void onFacebookError(FacebookError e) {...}
    public void onError(DialogError e) {...}
    public void onCancel() {...}


The result of this call is the Facebook web-based publish to wall dialog as in Posting to the wall.

Posting to the wall

Screen capture of posting to the wall dialog

This is the familiar Web page for posting to the user’s wall as served by Facebook. The user can skip or go ahead and publish the message. This use of native and web content together within the same mobile application is a great example of the power of hybrid applications.

Authorizing users

The Facebook Platform provides support for OAuth 2.0 authentication as well as support for an older, custom authorization signature scheme. You should avoid using the older authentication scheme when writing new applications as support for this older scheme will not be available in the near future. For more information about OAuth, see the OAuth 2.0 Protocol specification in Related links.

The Facebook SDK for Android together with the Facebook Platform hides the complexity of OAuth authentication as illustrated in The OAuth 2.0 Protocol (IETF).

The OAuth 2.0 Protocol (IETF)

Diagram of the OAuth 2.0 Protocol (IETF)

The Facebook SDK for Android takes a mobile web approach to authentication rather than a native one. Note that it is possible that future versions of the SDK will provide native Android support for OAuth. For this approach, the SDK uses the Facebook web-based authentication dialog inside a WebView. This is an interesting approach for a couple of reasons:

  • It reduces the complexity of implementing OAuth native to the application.
  • Probably as important, it wins the user’s trust by displaying the same standard and familiar login and permission dialogs as seen when using Facebook on regular browsers.

One disadvantage of this approach is that it might feel slower sometimes than a pure native implementation. For this, the SDK includes an alternative authentication/login approach that uses the native Facebook application’s single sign-on. This is, if the official Facebook native application is installed on the handset, the Facebook SDK for Android can use its authorization/login Activity. But to make this work, you must first sign your application, then generate a signature or key hash (see Generating the application key hash).

Generating the application key hash
keytool -exportcert -alias [alias] -keystore [keystore] | openssl sha1 -binary |
                                                                          openssl base64

Note that the code in Generating the application key hash normally appears on a single line. It is split to multiple lines for formating purposes.

You must then register the generated key hash on Facebook for your particular application under the mobile and devices section as in Enter the application key hash. (View a larger version of Enter the application key hash.)

Enter the application key hash

Screen capture of Key hash field)

Once registered, you must define an “activity result handler” for your application; implement onActivityResult(...) on which you must invoke the method facebook.authorizeCallback(...) as in Defining an activity result handler).

Defining an activity result handler
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  facebook.authorizeCallback(requestCode, resultCode, data);
  // ... Other onActivityResult steps per your app...

Note that if the single sign-on method is not defined or the native Facebook application is not present, the SDK will default to the WebView approach for authentication/login. The rest of the article focuses on this default approach.

As previously mentioned, by default an application has access to all public data in the user’s profile. To access private data, the application must request and the user must grant to the application permissions to do so. The permissions to gain access to private data are referred to as Extended Permissions.

The Facebook SDK for Android authorize() method implements the OAuth 2.0 User-Agent flow to retrieve an access token for use in subsequent API requests. The method starts either an Activity (native Facebook app, if present and configured) or a the WebView dialog to prompt the user for credentials (authentication) and permissions (authorization), see The authorize method).

The authorize method
 * Authorize method that grants custom permissions.
public void authorize(Activity activity, String[] permissions,
        final DialogListener listener) {

Note that for the single sign-on authentication to properly work, you must include a call to the authorizeCallback() method in your onActivityResult() function.

Recall from Handling the menu selection how the login menu item invokes the authorize() method with permissions.

Call the authorize() method with permissions shows how to invoke the authorize() method with permissions to write content. It also has permission to write comments and likes (publish_stream), read the user’s feeds, perform searches (read_stream), and make the access credentials long-lived (offline_access). Don’t forget to set your APP_ID.

Call the authorize method with permissions

public static final String APP_ID = "13234...";

private static final String[] PERMISSIONS = new String[] {"publish_stream",
        "read_stream", "offline_access"};


// Call the authorization method
    new MyLoginDialogListener());


// Asynchronous Callback when authorization completes
private final class MyLoginDialogListener implements
          .Facebook.DialogListener {

    public void onComplete(Bundle values) {...} // here enable logout
    public void onFacebookError(FacebookError error) {...}
    public void onError(DialogError error) {...}
    public void onCancel() {...}

The authorize() method internally invokes the dialog() method previously covered, but this time it passes a Login request for action. With the help of the Facebook Platform and its implementation of OAuth, the authorize() method also takes care of the authentication request to Facebook and returns the access_token that is used throughout the Facebook session and API invocation:

For detailed information on how authentication works, see the Facebook Authentication page in Related links.

Calling the authorize() method results in the WebView-based dialogs in The authorize and permissions screens (WebView).

The authorize and permissions screens (WebView)

Screen capture of WebView-based dialogs

After the user logs in, she is prompted for permissions (email or phone information and a password) as requested by the application. The user can allow or deny the application permission to access her Facebook and do such actions as access basic information, post to the user’s Wall, access posts in the News Feed, or Access user data.

Making Facebook API requests

The core Facebook class implements a number of request() methods for Old REST and Graph API calls. In addition, the SDK provides helper wrapper classes to make the core request API calls asynchronous.

As an example of an API request, you will make a request to retrieve the friends for the authenticated user. Recall the structure of a Graph API:

Also, recall the special ID me that is used to identify the authenticated user; the user has logged in:

Dispatching a request asynchronously shows a snippet from Handling the menu selection on how to make the request() method call. In this example, you use the AsyncFacebookRunner.request(...) method, which is a helper wrapper method to make the underlying request method asynchronous by running in its own thread. This step is done to avoid blocking the main UI thread.

Dispatching a request asynchronously
// Get Friend's List
case // Wall Post
    // Get the authenticated user's friends;
    mAsyncRunner.request("me/friends", new FriendsRequestListener());

The FriendsRequestListener onComplete(...) callback is invoked when the request to get the friend’s list finishes executing. This method parses the returned JSON for the list of friends. Note that Processing the get friends request does not show all of the implemented methods.

Processing the get friends request
 * FriendsRequestListener implements a request lister/callback
 *  for "get friends" requests
public class FriendsRequestListener implements {

     * Called when the request to get friends has been completed.
     * Retrieve and parse and display the JSON stream.
    public void onComplete(final String response) {
        try {
            // process the response here: executed in background thread
            Log.d("Facebook-Example-Friends Request", "response.length(): " +
            Log.d("Facebook-Example-Friends Request", "Response: " + response);

            final JSONObject json = new JSONObject(response);
            JSONArray d = json.getJSONArray("data");
            int l = (d != null ? d.length() : 0);
            Log.d("Facebook-Example-Friends Request", "d.length(): " + l);

            for (int i=0; i<l; i++) {
                JSONObject o = d.getJSONObject(i);
                String n = o.getString("name");
                String id = o.getString("id");
                Friend f = new Friend();
       = id;
       = n;

            // Only the original owner thread can touch its views
            SampleApp.this.runOnUiThread(new Runnable() {
                public void run() {
                    friendsArrayAdapter = new FriendsArrayAdapter(
                            SampleApp.this, R.layout.rowlayout, friends);
        } catch (JSONException e) {
            Log.w("Facebook-Example", "JSON Error in response");


According to your application requirements, the response from the Facebook servers, which is in JSON format, must be parsed and processed accordingly. You might decide to display such information by using a WebView or by using a ListView as in this SampleApp (see Displaying the results).

Displaying the results

Screen capture of a list of names and IDs displayed as results


In this article, you looked at Facebook APIs. You began with a general overview of the Facebook Platform and its APIs, followed by the Facebook SDK for Android and a sample application. With this information, you now have a better understanding of the different Facebook APIs that are available and of how to start writing Facebook applications for the Android platform.

Download Article source code