Getting started with the Facebook for Android SDK

Many mobile apps allow the user to post content to popular social media platforms, such as Facebook, Twitter and LinkedIn.

This kind of social sharing can be a great way to promote your app, and can improve the user experience by creating a connection between your application and the user’s favorite social media networks.

To promote social sharing, many of the major social platforms have created tools that specifically target app developers – and Facebook is no exception!

In this article, I’ll show you how to add Facebook integration to your Android applications, using the Facebook for Android SDK (Software Development Kit). Once you’re connected to the official Facebook SDK, you’ll have access to a wide range of features, but in this article we’ll be focusing on two of the most popular: authenticating with Facebook, and social sharing.

By the end of this article, you’ll have created an application that allows users to authenticate their identify using their Facebook credentials, and then share your app’s content, by posting it to Facebook.

Add Facebook integration to your app, using the Facebook SDK

What is the Facebook for Android SDK?

Every social media platform wants to drive user engagement, and enabling users to share content from a range of sources is a powerful way to keep them engaged with your platform.

The official Facebook SDK for Android helps you create apps that integrate with Facebook, and provides access to several key features, including Facebook authentication, and reading and writing to the platform’s APIs.

The Facebook SDK for Android compromises of the following components:

  • Analytics. Provides access to aggregated and anonymized data, so you can analyze how people are using your app.
  • Login. Allows people to sign into your app using their Facebook credentials. If the user is already signed into the Facebook for Android mobile app, then they won’t have to re-enter their username and password, in order to authenticate with your application. Once a user is signed in with Facebook, you can retrieve information and perform actions on their behalf, such as displaying their Facebook profile pic inside your app, or posting status updates.
  • Account Kit. Makes it possible for users to authenticate their identify, using just their phone number or email address. Account Kit doesn’t require a Facebook account, which makes this a viable authentication method for any users who haven’t signed up to Facebook.
  • Ads. If you want to monetize your application, then you can use this component to create and run ad campaigns.
  • App events. Allows you to track a range of user actions and events within your app. You can use this information to evaluate the effectiveness of your Mobile App Ads, or to identify the users who are most likely to respond to your adverts.
  • App Links. Imagine a user has just posted some of your app’s content to Facebook; App Links let you specify what happens, when someone interacts with this content. For example, they might get forwarded to your app’s Google Play listing, or your company’s website. Alternatively, if someone already has your app installed on their device, then you may respond by launching your application, and taking them to an Activity related to this content.
  • Graph API. By integrating with the Facebook Graph API, you can retrieve data from the Facebook platform, and add data such as posting new stories and uploading photos.

What are the benefits of Facebook integration?

For developers, the Facebook for Android SDK has several benefits.

1. Seamless sign up

Depending on your application, users may need to authenticate their identity before they can access certain features. Even if your application only requires an email address and password, there’s always going to be a percentage of mobile users who decide this is too much hassle, and exit your application.

There’s several reasons why we’re much less likely to complete a registration form on a mobile device, compared to our laptop or computer. Firstly, we tend to use smartphones and tablets on the go, and often under time constraints, for example you might spend a few minutes playing on your phone while you’re waiting at the doctor’s office, in line at the supermarket, or at your local bus stop. None of these scenarios are ideal for completing an in-app form!

In addition, typing on your mobile device’s small, virtual keyboard can be time-consuming and frustrating, particularly for users who have manual dexterity issues, or anyone who’s prone to typos. Typing a password that contains a mixture of symbols, numbers, and upper and lowercase letters, can feel like a huge effort on your smartphone or tablet.

By adding Facebook login to your application, you can replace an in-app registration form, with single-tap authentication.

Your users can authenticate their identity, using their Facebook credentials

By reducing the amount of time and effort required to authenticate the user’s identify, you should see an increase in the number of people who successfully complete your app’s registration process.

2. Drives traffic and user engagement

Another major feature of the Facebook SDK, is allowing users to share your application’s content. Shared content will appear on the user’s Facebook Timeline and in their friends’ News Feed, potentially exposing your app to an entirely new audience.

Ideally, the user’s Facebook friends will engage with this shared content in some way – whether that means making a note of your application’s name, or tapping the shared content. Although we won’t be exploring it in this tutorial, you can use Facebook’s App Links component to specify what happens when someone interacts with this shared content, for example you might take them to your app’s Google Play listing.

If a user already has your application installed, then you could even link each piece of shared content, to a different Activity within your app. Creating a link between shared content and some relevant in-app content, can be an effective way to drive traffic, and re-engage users who might have otherwise lost interest in your app.

3. Improves the user experience

Even something as simple as making it easier to share your app’s content, can have a positive impact on the user experience. Imagine someone has invested hours into achieving a high score in a mobile game, and they want everyone to know about it! You could improve their experience, by making it easy for them to post their high score to Facebook.

Integrating the Facebook SDK into your application can also be the first step to designing more complex features, or enhancing your app’s existing functionality. For example, if you’re creating a messaging app, then you could ask the user to manually enter the contact information for all of their friends and family, or you could create an “automatic import” feature that pulls relevant data from their Facebook friends list.

While it’s unlikely that every single one of the user’s Facebook friends will have their full name, address and telephone number listed on their profile, this feature will reduce how much information the user has to input manually, which is going to improve their user experience.

Getting started: Creating a Facebook Developer account

In this article, we’ll be creating an application that allows the user to authenticate their identify using their Facebook credentials, and then share some of your application’s content, in the form of a Facebook status update.

Start by creating an Android app using the “Empty Activity” template. Once we have our app, we need to assign it a Facebook App ID, which requires a Facebook developer account.

Facebook developer accounts are free to create, so if you aren’t already registered with Facebook for Developers then:

  • Head over to the Facebook for Developers website.
  • In the upper-right corner, select “Log In.”
  • Enter your Facebook username and password, and then follow the onscreen instructions to create your account.

Registering your app with Facebook

Next, we need to create a Facebook App ID for this project:

  • The Facebook for Developers website has an entire section dedicated to helping you integrate Facebook into your Android app, so let’s make life easier for ourselves and head over to Quick Start for Android.
  • If prompted, enter your Facebook login details.
  • In the text field, give your Facebook App a distinctive name.
  • When it appears, select “Create New Facebook App ID.”

Create a new Facebook App ID

  • Enter a display name for your application, and your email address.
  • Click “Create App ID.”
  • Next, we need to add the Facebook SDK as a build dependency, so switch back to Android Studio, and open your build.gradle file. Tell your project to compile the latest version of the Facebook SDK, by adding the following to its “dependencies” section:
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' //Add the following// implementation 'com.facebook.android:facebook-android-sdk:4.33.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' implementation 'androidx.fragment:fragment:1.0.0'
}
  • When prompted, sync your changes.
  • Switch back to your web browser, and the Quick Start for Android webpage should be displaying a Facebook App ID that you can add to your Android project. Copy this value, and then switch back to Android Studio.
  • Open your project’s strings.xml file, and create a “facebook_app_id” string that references your unique Facebook App ID:
<string name="app_id">REPLACE-WITH-YOUR-UNIQUE-VALUE</string>
  • Communicating with Facebook requires Internet access, so open your Manifest and add the following:
<uses-permission android:name="android.permission.INTERNET" />
  • While we’re in the Manifest, add the following <meta-data> to the <application> element:
 </activity> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id" /> <meta-data android:name="com.facebook.sdk.ApplicationName" android:value="@string/app_name" /> </application>
</manifest>
  • Flick back to your web browser and scroll to the bottom of the Quick Start for Android guide; you should spot a “Tell us about your Android project” section.

Enter your project's package name and default Activity class name

  • Enter your Android project’s package name, which you’ll find at the top of its Manifest file.
  • In the “Default Activity Class Name” field, enter the fully qualified class name of the Activity that handles deep linking in your app. In my project, the deep linking Activity is MainActivity.
  • Click “Next.”
  • At this point, you’ll be warned that this package name isn’t registered on Google Play, which makes sense since we haven’t published our project yet! You can ignore this warning by clicking “Use this package name.”

Tracking installs, launches and Google Play purchases

At this point, you have the option to disable “Log In-App Purchase Events Automatically on Android.”

When you use the Facebook SDK, certain app events and actions are automatically recorded by Facebook Analytics, unless you explicitly disable event logging.

By default, all of the following events and actions will be logged, and then displayed in your app’s Insights dashboard:

  • App Installs. The first time a user activates your application, or the first time your app is launched on a new device.
  • App Launch. Someone launches your application.
  • Purchase. A user completes an in-app purchase via Google Play. If you use an alternative payment platform, then in-app purchases will not be logged unless you write your own purchase event code. If you’re already logging in-app purchases using an alternative method, then just be aware that Facebook SDK’s logging can result in duplicate entries. If you’re already tracking app purchases, then it’s recommended that you find the “Log In-App Purchase Events Automatically on Android” slider, and push it into the “Off” position.

To record additional events and actions, check out Codeless App Events.

How to generate a development key hash

To ensure the authenticity of the interactions between your application and Facebook, the Quick Start for Android will request the Android key hash for your development environment.

If you’re running macOS, then:

  • Open a new Terminal window.
  • Copy/paste the following command into the Terminal:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
  • Press the “Enter” key on your keyboard.

If you’re a Windows user, then:

  • Launch the Command Prompt.
  • Copy/paste the following command:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64
  • Press the “Enter” key on your keyboard.

Both of these commands will generate a 28 character key hash that’s unique to your development environment. Copy this value, and then switch back to the Quick Start for Android guide and paste it into the “Key hashes” field.

Generate a release key hash, and add it to the Quick Start for Android guide

Note that if multiple people are working on this project, then you’ll need to generate a key hash for each individual development environment.

Once you’ve entered your key hash, click “Next” and you should see a “Finished” message. Congratulations, you’ve laid the groundwork for creating an Android application that integrates with Facebook!

Authenticate with Facebook: Adding a LoginButton

The first feature we’re going to implement, is authenticating with Facebook.

You can add Facebook authentication to an Android app, using the LoginButton that’s conveniently included in the Facebook SDK. LoginButton is a custom view implementation of Button, which wraps functionality available in the LoginManager. Every time the user taps the LoginButton, LoginManager will initiate the login process with the requested read or publish permissions.

We create a LoginButton, by adding a “com.facebook.login.widget.LoginButton” element to our layout. While I’m editing my activity_main.xml file, I’m also going to add a regular button, which will eventually allow the user to update their Facebook status.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:facebook="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.facebook.login.widget.LoginButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_gravity="center_horizontal" facebook:com_facebook_tooltip_mode="never_display" facebook:com_facebook_confirm_logout="false" /> <Button android:id="@+id/postStatusUpdate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Post Status Update" /> </LinearLayout>

Working with the Facebook SDK: Authentication and sharing

In our MainActivity, we need to:

  • Initiate the Facebook authentication process and handle the outcome, including any errors that may occur.
  • Provide some content for the user to share.
  • Provide a mechanism for sharing this content.

Implementing login with Facebook

The first step to handling the Facebook login response, is to create a connection between the LoginButton in our layout, and the Facebook SDK:

 LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

FacebookCallback handles each possible login attempt, using the following methods:

  • onSuccess. The login attempt was successful.
  • onCancel. The user cancelled the login attempt.
  • onError. An error occurred.

We need to implement each of these methods:

 @Override public void onSuccess(LoginResult loginResult) { //To do// } @Override public void onCancel() { //To do// } @Override public void onError(FacebookException exception) { //To do// }

Next, we need to initialize an instance of CallbackManager using the CallbackManager.Factory.create method. This callback will be responsible for routing calls back to the Facebook SDK and our registered callbacks:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Create a callbackManager// callbackManager = CallbackManager.Factory.create();

Tapping the login button will start a new Activity, which returns a result. In order to process this login result, we need to override our onActivityResult method and pass its parameters to the onActivityResultmethod of CallbackManager.

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //Forward onActivityResult to the callbackManager// callbackManager.onActivityResult(requestCode, resultCode, data); }

Check the login status

Only one person can be logged into our application at a time. LoginManager sets the AccessToken and Profile for the user who is currently signed in with Facebook, and the Facebook SDK saves this information in shared preferences at the beginning of each session.

We can check whether someone is currently logged in with Facebook, using AccessToken.getCurrentAccessToken() or Profile.getCurrentProfile().

Every time our application launches, I’m going to load AccessToken.getCurrentAccessToken and check its validity:

 private boolean hasPublishActionPermission() { return AccessToken.isCurrentAccessTokenActive() && //Check for publish permissions// AccessToken.getCurrentAccessToken().getPermissions().contains("publish_actions"); }

Create shareable content

Now we’ve handled the Facebook login, we need to provide some content that our users can share, by posting it to Facebook.

The Facebook SDK can support shared content in the form of links or multimedia, such as photos or videos, but to help keep things simple we’ll be sharing a single URL.

We can build an instance of our link, using ShareLinkContent.Builder:

 ShareLinkContent linkContent = new ShareLinkContent.Builder()

Next, we need to describe the link’s content, using setContentURL:

 .setContentUrl(Uri.parse("https://www.androidauthority.com/"))

Finally, we can build our link:

 .build();

You can also add an image, a caption, a description and other attributes to your shared content.

ShareDialog: Communicating with the native Facebook app

Facebook’s ShareDialog allows users to post your application’s content to their Timeline, a friend’s profile, or a Facebook group. ShareDialog fully supports Facebook’s post model, so users can tag friends and places in your application’s shared content.

The ShareDialog is one of the easiest ways to implement Facebook sharing in your app, and also provides a native sharing experience. When the ShareDialog is triggered, the Facebook SDK automatically redirects the user to the native Facebook for Android app, where they can edit and publish their post, as normal. Once the user has published their post, the Facebook SDK will redirect them back to your app.

Since this experience takes place within the native Facebook application, ShareDialog will function correctly even if the user hasn’t connected your app to their Facebook account – assuming they have Facebook for Android installed on their device!

If the user hasn’t installed the native Facebook app, then the Facebook SDK will fall back on the Feed dialog, which launches the web-based version of Facebook in the device’s default web browser. Note that if your application reverts to the Feed dialog and the user isn’t currently logged into Facebook within their web browser, then they’ll be prompted to enter their Facebook credentials.

Start by creating a ShareDialog instance:

 private ShareDialog shareDialog;
...
...
... shareDialog = new ShareDialog(this); shareDialog.registerCallback( callbackManager, shareCallback);

We can then display this dialog:

 ShareLinkContent linkContent = new ShareLinkContent.Builder() .setContentUrl(Uri.parse("https://www.androidauthority.com/")) .build(); if (canDisplayShareDialog) { shareDialog.show(linkContent);

The completed MainActivity

After performing all the above tasks, your MainActivity should look something like this:

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.fragment.app.FragmentActivity; import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.Profile;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.widget.ShareDialog;
import com.facebook.share.model.ShareLinkContent; public class MainActivity extends FragmentActivity { private final String PENDING_ACTION_KEY = "com.jessicathornsby.facebooksample:PendingAction"; private boolean canDisplayShareDialog; private Button postStatusUpdate; private CallbackManager callbackManager; private PendingAction pendingAction = PendingAction.NONE; //Declare a private ShareDialog variable// private ShareDialog shareDialog; //The result of the “share” action// private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() { //The user cancelled the share// @Override public void onCancel() {
//To do// } //An error occurred// @Override public void onError(FacebookException error) {
//To do// } //The content was shared successfully// @Override public void onSuccess(Sharer.Result result) { //To do// } }; private enum PendingAction { NONE, POST_STATUS } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Initialize an instance of CallbackManager// callbackManager = CallbackManager.Factory.create(); //Register a callback to respond to the user// LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { handlePendingAction(); updateUI(); } @Override public void onCancel() { if (pendingAction != PendingAction.NONE) { showAlert(); pendingAction = PendingAction.NONE; } updateUI(); } @Override //Handle exception// public void onError(FacebookException exception) { if (pendingAction != PendingAction.NONE && exception instanceof FacebookAuthorizationException) { showAlert(); pendingAction = PendingAction.NONE; } updateUI(); } //Display an error message// private void showAlert() { new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.cancelled) .setMessage(R.string.FBexception) .setPositiveButton(R.string.ok, null) .show(); } }); //Create the ShareDialog// shareDialog = new ShareDialog(this); //Callback registration// shareDialog.registerCallback( callbackManager, shareCallback); if (savedInstanceState != null) { String name = savedInstanceState.getString(PENDING_ACTION_KEY); pendingAction = PendingAction.valueOf(name); } setContentView(R.layout.activity_main); postStatusUpdate = (Button) findViewById(R.id.postStatusUpdate); //Listen for the user tapping the postStatusUpdate button// postStatusUpdate.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { onClickPostStatus(); } }); //Share link callback// canDisplayShareDialog = ShareDialog.canShow( ShareLinkContent.class); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(PENDING_ACTION_KEY, pendingAction.name()); } @Override //Override the onActivityResult method// protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //Pass the login result to the CallbackManager// callbackManager.onActivityResult(requestCode, resultCode, data); } private void updateUI() { boolean enableButtons = AccessToken.isCurrentAccessTokenActive(); postStatusUpdate.setEnabled(enableButtons || canDisplayShareDialog); } private void handlePendingAction() { PendingAction previouslyPendingAction = pendingAction; pendingAction = PendingAction.NONE; switch (previouslyPendingAction) { case NONE: break; case POST_STATUS: postStatusUpdate(); break; } } //Check for publish permissions// private boolean hasPublishActionPermission() { return AccessToken.isCurrentAccessTokenActive() && //Load AccessToken.getCurrentAccessToken// AccessToken.getCurrentAccessToken().getPermissions().contains("publish_actions"); } private void publish(PendingAction action, boolean allowNoToken) { if (AccessToken.isCurrentAccessTokenActive() || allowNoToken) { pendingAction = action; handlePendingAction(); } } private void onClickPostStatus() { publish(PendingAction.POST_STATUS, canDisplayShareDialog); } private void postStatusUpdate() { Profile profile = Profile.getCurrentProfile(); //Build an instance of our link// ShareLinkContent linkContent = new ShareLinkContent.Builder() //Describe the link’s content// .setContentUrl(Uri.parse("https://www.androidauthority.com/")) //Build the link// .build(); //Display the ShareDialog// if (canDisplayShareDialog) { shareDialog.show(linkContent); } else if (profile != null && hasPublishActionPermission()) { ShareApi.share(linkContent, shareCallback); } else { pendingAction = PendingAction.POST_STATUS; } } }

Creating our Facebook error message

We reference a few string resources in our MainActivity class, which will be displayed if an error occurs. Open your strings.xml file and add the following:

 <string name="cancelled">Cancelled</string> <string name="ok">OK</string> <string name="FBexception">FacebookAuthorizationException.</string>

Testing your Facebook integration

To test your project’s Facebook integration, you’ll need to have the native Facebook for Android app installed on your device.

If you’re using an Android Virtual Device (AVD), then you’ll need to load the Google Play store and download Facebook to your AVD, exactly as you would on a physical device. You’ll then have to launch the Facebook for Android app and enter your Facebook login details.

Once you have a compatible Android device or AVD:

  • Install this project on your Android device.
  • Once the application loads, tap its “Continue with Facebook” button.
  • After a few moments, your Facebook profile picture and full name should appear; if this information is correct, then click “Continue.” You’re now logged into Facebook.
  • To share some content to Facebook, tap the “Post Status Update” button. The native Facebook for Android app should now appear, with a new status already created for you.

You can use the Facebook SDK to make your app's content shareable

You can download the finished project from GitHub.

Note that you’ll need to open the project’s strings.xml file and update <string name=”app_id”>YOUR-APP-ID-HERE</string> with your own Facebook App ID.

Ready to publish your app? Generating a release key hash

When it’s time to publish your app, you’ll need to digitally sign it with a release key before uploading it to Google Play. However, if your app uses the Facebook SDK then you’ll also need to generate a release key hash, and add it to your Facebook App ID settings. If you skip this step, then there’s a chance that none of your app’s Facebook SDK features will work correctly.

To generate a release key hash on macOS, launch the Terminal and run the following command:

keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64

Don’t forget to substitute <RELEASE_KEY_ALIAS> with your own release key alias, and <RELEASE_KEY_PATH> with the path to your keystore.

If you’re a Windows user, then open your Command Prompt and run the following command:

keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | PATH_TO_OPENSSL_LIBRARY\bin\openssl sha1 -binary | PATH_TO_OPENSSL_LIBRARY\bin\openssl base64

Again, you’ll need to update <RELEASE_KEY_ALIAS> and <RELEASE_KEY_PATH> with your own values.

When prompted, enter the password that you used to create your release key.

Once you have your release key hash, you can add it to your Facebook App ID’s Android settings:

  • In your web browser, head over to the Facebook for Developers “All Apps” page.
  • Select your Android app’s corresponding Facebook app. If you’re unsure which Facebook app is linked to your Android application, then check the “App ID” value defined in your strings.xml file – the correct Facebook app will have the exact same value.
  • In the left-hand menu, select “Settings,” followed by “Basic.”

Don't forget to generate a release key hash, before publishing your app

  • Scroll to the “Android” section.
  • Find the “Key hashes” box, and copy/paste your release key hash into this box.
  • Click “Save changes.”

You should now be able to publish your app to Google Play, without any issues.

Wrapping up

In this article, we created an Android application that integrates with Facebook, via the official Facebook for Android SDK, and then used this SDK to implement two of the most popular Facebook features: authentication, and social sharing.

Once you’ve added the Facebook SDK to your Android project, you’ll have access to plenty of additional Facebook features, including analyzing user demographics, creating targeted Mobile App Ads, and using the Graph API to exchange data with the Facebook platform. If you want to continue exploring the Facebook SDK, then you’ll find lots of additional information over at the Facebook for Developers docs.

Do you plan to use the Facebook SDK in your own Android applications? Let us know in the comments below!

Leave a Reply