Smartphones

Integrate Facebook logins in your Android app

Kyle Miller provides mobile developers with instructions on how to integrate Facebook logins into their Android applications.

One of the easiest ways to get users to log in to your application is by letting them use their Facebook account to do so. In my experience, most people will opt to re-use their Facebook login, which I can understand because I don't always want to create a new account for every app I use.

I will walk you through the process of integrating Facebook logins in your Android application. The setup involved is fairly straightforward. I suggest that you first check out the sample source code for this article that I posted on GitHub.

Create a Facebook app

The first step is to create an application in Facebook. You can do this by going to the Developer App once you are logged in to Facebook.

From the developer portal, click the + Create New App button at the top right. Give the app a name, agree to their terms by clicking the checkbox, and then click the Continue button. Complete the Captcha test and then click the Continue button.

You will then be taken to a screen where you can edit all the details for your Facebook app. Click the Mobile link in the left-hand nav, as this is the only section we will be interested in. Take note of the App ID, because you will need this later when coding your Android app.

Next, you will need to generate a Key Hash for the application. For debugging, if using Eclipse, you will want to generate this Key Hash using the Android debug key. When you are ready to publish your app, you will need to generate a Key Hash for your signing keys and update this value in Facebook before your signed app will work.

To generate a Key Hash for your debug keys, first open a command prompt (Windows) or terminal (Mac). Navigate in the command-line to the directory where your Android debug keystore is stored. On Windows it will be "C:\Documents and Settings\<User>\.android" and on a Mac it will be in "~/.android".

Once you are in the ".android" directory, run the following command. When it prompts you for a password, type android and hit Enter:

keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64

Copy the value printed in the command-line that ends with an "=" and paste it in the Key Hash field in Facebook. Then click the Save Changes button.

Copy the necessary Android assets

Now you are ready to start integrating Facebook login in your Android application. Before you do this, you need to make sure you have installed the official Facebook APK, which you'll find on the Android Market.

Copy the /src/com/facebook folder of my sample code into the /src/com folder of your Android project. Also copy the facebook_icon.png image file from the drawable folder of my sample into the drawable folder of your project. Then, edit the FbDialog.java file to change the package name of the following line:

import com.kmiller.facebookintegration.R;

Next, copy /src/com/kmiller/facebookintegration/SessionStore.java and /src/com/kmiller/facebookintegration/Util.java into your project and fix the package name in each file.

Authorize/query Facebook

The Login.java file of my sample application contains all the logic for authorizing the user and to query Facebook afterwards. Here's a look at the various sections of that file to examine the responsibility of each part.

mAPP_ID
public static final String mAPP_ID = "<your_app_id>";

You should replace this value with the App ID of the Facebook app you created in the beginning.

onCreate
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

((Button)findViewById(R.id.LoginButton)).setOnClickListener( loginButtonListener );

SessionStore.restore(mFacebook, this);

}

The call to SessionStore.restore() will restore a previous Facebook session (if it was stored properly in the first place) so you won't have to re-authorize the user.

onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

mFacebook.authorizeCallback(requestCode, resultCode, data);

}

This method gets called after the user is returned from Facebook authorization. The one line of code in this method simply passes the results of onActivityResult to the mFacebook object's authorizeCallback method.

loginButtonListener
private OnClickListener loginButtonListener = new OnClickListener() {
public void onClick( View v ) {
if( !mFacebook.isSessionValid() ) {
Toast.makeText(Login.this, "Authorizing", Toast.LENGTH_SHORT).show();
mFacebook.authorize(Login.this, new String[] { "" }, new LoginDialogListener());
}
else {
Toast.makeText( Login.this, "Has valid session", Toast.LENGTH_SHORT).show();
try {
JSONObject json = Util.parseJson(mFacebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
Toast.makeText(Login.this, "You already have a valid session, " + firstName + " " + lastName + ". No need to re-authorize.", Toast.LENGTH_SHORT).show();
}
catch( Exception error ) {

Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();

}

catch( FacebookError error ) {

Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();

}

}

}

};

When the user clicks the "Login with Facebook" button in the sample application, this is the OnClickListener that fires. It starts by checking if there is a valid Facebook session. If there is not a valid Facebook session, mFacebook.authorize is called. Otherwise, it queries Facebook using mFacebook.request("me") to get the user's first and last name.

LoginDialogListener
public final class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
try {
//The user has logged in, so now you can query and use their Facebook info
JSONObject json = Util.parseJson(mFacebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
Toast.makeText( Login.this, "Thank you for Logging In, " + firstName + " " + lastName + "!", Toast.LENGTH_SHORT).show();
SessionStore.save(mFacebook, Login.this);
}

catch( Exception error ) {

Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();

}

catch( FacebookError error ) {

Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();

}

}
public void onFacebookError(FacebookError error) {

Toast.makeText( Login.this, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();

}
public void onError(DialogError error) {

Toast.makeText( Login.this, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();

}
public void onCancel() {

Toast.makeText( Login.this, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();

}

}

If the login is successful, the onComplete method of the DialogListener will fire. At this point, you may query Facebook for the user's information since you now have a valid session. You should also call SessionStore.save() to save this current session to keep from re-requesting authorization in the future.

If the login fails, the onFacebookError, the onError, or the onCancel method will be fired, and you can handle it appropriately. Your app should now be capable of the basics regarding Facebook authorization.

For more information on this topic, check out the Mobile Apps section on the Facebook Developers page.

If you're interested in me expanding the sample app to show some of the deeper Facebook integration that is possible, please let me know in the discussion.

About

Kyle is a senior software engineer specializing in web/Android development living in Austin TX. He's a self-professed "gadget freak" whose passion for mobile devices drove him to jump into the mobile industry in 2010. He enjoys the fast-paced nature ...

5 comments
anil_654321
anil_654321

now how to log out from that facebook a/c from my android app.

anil_654321
anil_654321

now how to log out on facebook server from my android app.

poly89
poly89

I'm new to Android programming and that was very useful tutorial but i have a problem .... when i run it , there cames an error : Unreachable catch block for FacebookError. It is already handled by the catch block for Exception . : catch( Exception error ) { Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show(); } catch( FacebookError error ) { Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show(); } if anybody could help me with that i would be great!!!!!

NovaSev
NovaSev

First off all, I'm still pretty new to Android programming. Essentially I can develop an App and work with many of the issues I encounter but I'm not good at all with any connection issues. This is an awesome, tutorial i suppose you would say - but I'm having some issues. I've gotten the proper Hash Key, APP_ID from FB and all that but can't get it to work. When running it through the emulator it works fine and continues to do so, but after uploading the App to the market and installing it I can't log in to save my life. This is my first app and I'm hoping to get it functioning at least. Any help/ideas would be appreciated.

Editor's Picks