Wednesday 17 August 2011

Getting started with the Android Facebook SDK

First thing to do is to link the Android Facebook SDK to your Android project.

Next, reference a Facebook object somewhere in your Android project code and add a method to initialise it with your Facebok app id. For example:

private static Facebook facebook;
public static void initialise(String facebookAppId) { facebook = new Facebook(facebookAppId); }

Before you can get or post any data from Facebook, you will need to initialise your Facebook object instance (using the method above for example) and then call one of the Facebook class authorize(...) methods for your app to be granted permissions to make Facebook api calls. For example:

facebook.authorize(MyActivity.this, new String[] { "publish_stream" }, new Facebook.DialogListener() { /* add implementation of DialogListener interface methods */ });

Once permissions are granted (i.e. authorisation is successful), you can start making requests to the Facebook api using the AsyncFacebookRunner class. For example, to get details of the current user, do the following:

new AsyncFacebookRunner(facebook).request("me", new AsyncFacebookRunner.RequestListener() { /* add implementation of RequestListener interface methods */ }

Or, similarly, to post a message to the current user's wall, do the following, where you can find an example of how to set up bundleParams in the comments below:

new AsyncFacebookRunner(facebook).request("me/feed", bundleParams, "POST", new AsyncFacebookRunner.RequestListener() { /* add implementation of RequestListener interface methods */  }, new Object());

Lastly, to log out the currently signed in user from Facebook, call the Facebook class logout(Context) method, passing the Context that was used to do the login (authorisation). For example:

facebook.logout(MyActivity.this);

That's it! That's the basics of using the Android Facebook SDK.

1 comment:

adil said...

Example of the Bundle parameters that can be passed to the AsyncFacebookRunner request method for posting to a user's wall:

Bundle bundleParams = new Bundle();

bundleParams.putString("caption", "The caption to go with the link.");

bundleParams.putString("description", "The description to go with the link.");

bundleParams.putString("link", "http://somelink.com");

bundleParams.putString("message", "The message to post");

bundleParams.putString("name", "The name of the link");

bundleParams.putString("picture", "http://somelink.com/picture.png");