For posting score in Facebook using facebook sdk we first need to create an Android app for Facebook.
Go to Facebook Apps Page and login with the account from which you want to create the app.
Then go to Create New App and after clicking on it you would get a APP ID and APP SECRET and some basic details would have to be filled. It would look something like this.
We won’t using Open Graph so just the above details are enough for us to continue. Open graph is required if you want to access user friends etc from facebook but for posting score onto the user’s wall it is not required.
OpenSSL:
After facebook app is created we would have to generate a key hash for the facebook app. For generating keyhash we would require OpenSSL tool which is located in this OpenSSL download list.
Note for 64 bit users only openssl-0.9.8e X64 version works.
Extract it in any location and for our example we are extracting it in C:OpenSSL.
Then you have to find the location of debug.keystore. For win7 its located in C:Users{Username}.android.
If keytool.exe is not present in the PATH variable then find its location yourself. It is usually located in the bin folder of JDK
Open Command Prompt and run the following command in one line.
$ keytool -exportcert -alias androiddebugkey -keystore “C:Users{Username}.androiddebug.keystore” | “C:OpenSSLbinopenssl” sha1 -binary |”C:OpenSSLbinopenssl” base64
if prompted for password give “android”. Take the hash and update it in the app page like shown below.
Note:
This hash is generated from debug keystore so it would work while in testing mode but when you finally publish the application you would have to generate the key again from the release keystore (the keystore used to publish the application) and add that also in the facebook app page; this can be done as we are allowed to add more than one hash.
Integration Code:
We need the app id here, and we will also define the permissions we would require from the user.
[sourcecode language=”java”]
private static final String FB_APP_ID = "yourappnumericid";
private static final String FACEBOOK_PERMISSION = "publish_stream";
private static final int FB_AUTH=2; //ANY INTEGER VALUE
Facebook facebook = new Facebook(FB_APP_ID); //
static String FACEBOOK_UPDATE_MSG ;
static String FACEBOOK_UPDATE_FAILURE;
static String FACEBOOK_UPDATE_SUCCESS;
static String FACEBOOK_SIGNIN_FAILED;
Handler fHandler;
[/sourcecode]
For posting score we only need one facebook permission -> “publish_stream”.
Login:
Using the function below we initiate login to facebook. We would store the access_token in the preferences and while posting score we would just check if the token has value then we can use the token to access facebook. After authorizing we will post the score. This is a lazy way to login as we would only login to facebook if a user tries to post a score and not login at the application startup.
[sourcecode language=”java”]
public void login(final String msg){
String access_token=preferences.getString("facebook_access_token",null);
long expires = preferences.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires()
}
/*
* Only call authorize if the access_token has expired.
*/
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { FACEBOOK_PERMISSION },
FB_AUTH, new DialogListener() {
@Override
public void onComplete(Bundle values) {
preferences.putString("access_token",
facebook.getAccessToken());
preferences.putLong("access_expires",
facebook.getAccessExpires());
preferences.flush();
if(msg!="")
postMessageOnWall(msg);
else
OpenFbPage();
}
@Override
public void onFacebookError(FacebookError error) {
FACEBOOK_UPDATE_MSG = FACEBOOK_SIGNIN_FAILED;
fHandler.post(mUpdateFacebookNotification);
}
@Override
public void onError(DialogError e) {
FACEBOOK_UPDATE_MSG = FACEBOOK_SIGNIN_FAILED;
fHandler.post(mUpdateFacebookNotification);
}
@Override
public void onCancel() {
}
});
}
}
[/sourcecode]
OnActivityResult:
This code will be called on returning from login screen. FB_AUTH constant is used to recognize the activity when OnActivityResult is called after pressing login in the Facebook login popup.
[sourcecode language=”java”]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case FB_AUTH:
facebook.authorizeCallback(requestCode, resultCode, data);
break;
default:
finish();
break;
}
}
[/sourcecode]
PostScore:
We would run a new thread to post score in facebook.
[sourcecode language=”java”]
private void postMessageInThread(final String msg) {
Thread t = new Thread() {
public void run() {
try {
postMessageOnWall(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
[/sourcecode]
Then this function is called to post a message on the wall. In Libgdx we would have to add a function in the androidinterface which we defined in the tutorial Writing Android Specific code and from that function we can call the function below.
[sourcecode language=”java”]
public void postMessageOnWall(String msg) {
if (facebook.isSessionValid()) {
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("link","ANDROID_MARKET_LINK"); //or any other link
parameters.putString("name", "APP/GAME NAME");
try {
String response = facebook.request("me/feed", parameters,"POST");
FACEBOOK_UPDATE_MSG = FACEBOOK_UPDATE_SUCCESS;
fHandler.post(mUpdateFacebookNotification);
} catch (IOException e) {
FACEBOOK_UPDATE_MSG = FACEBOOK_UPDATE_FAILURE;
fHandler.post(mUpdateFacebookNotification);
}
} else {
login(msg);
}
}
[/sourcecode]
We added a function to post notifications on success/failure of the above task.
[sourcecode language=”java”]
final Runnable mUpdateFacebookNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), FACEBOOK_UPDATE_MSG,
Toast.LENGTH_LONG).show();
}
};
[/sourcecode]
Finally in OnDestroy function in android we would remove the token values.
[sourcecode language=”java”]
public void OnDestroy(){
//…..
if (preferences != null) {
preferences.putString("access_token", null);
preferences.putLong("access_expires", 0);
preferences.flush();
}
}
[/sourcecode]
So in this way we can post a score on the facebook wall.
will try it today, thanks!
What is FB_AUTH variable here
FB_AUTH is an integer value which would be used to detect the activity result in the “OnActivityResult” function. Thanks for pointing this out. I have the updated the post.
Thanks
This is really a very nice topic and there are no other good tutorial on this. Would you plz make this a little bit more clear..i.e. placement of codes. Where to place these code. I understood writing android code in libdx but … still having problems on where to place the code in Android main activity.
Thanks a lot !!! Not its great.
Which of the following methods should be defined in an interface so that it can be accessed in LibGdx Main Project.
I am also getting errors bcoz OpenFbPage(); is not defined…
and for the line fHandler.post(mUpdateFacebookNotification);
There is no post() method
fHandler is a Handler object. You can try out this post to understand how to run android specific code http://rotatingcanvas.com/writing-android-specific-code-in-libgdx/ and there is source code in this post to open a dialog from LibGdx game code http://rotatingcanvas.com/showing-dialog-in-libgdx-android/
Hope it helps.
Hi, thank you for your post. Unfortunately I was unable to integrate your code in my app. Please could you provide a working example to download and try? Thanks in advance! 🙂