Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Integrating Android Applications with Facebook

See in this article how to make your first integration with a Facebook App and an Android Application, in order to post content like images, text, links, etc. to the users timeline.

With the fever of social networks, it is clear that some applications (mainly those that are open to the public) require integration with leading social networks of the moment. Currently, who is at the peak is Facebook. Because of this, we will make the integration of one application developed under Android platform and this social network.

Registering our application

First, to be able to integrate your app with Facebook, you must have an account on the social network. Having a Facebook account, what is needed now is to register our application in it. To do this, we have to access the Facebook Developer page (available at Links section). Log in with your Facebook account (it's ideal that you don't use an account for personal use, but for systems development/tests) and after that, if you haven't registered already before, you'd be asked to register properly. So, click theRegister Now button, as shown in Figure 1.

Figure 1. Initial page of Facebook Developers.

After that you'll be prompted to accept the platform and privacy policies, so click Yes to accept and, the, Next button, as shown in Figure 2. You'll be then asked to fill some of your personal information, like country code, phone number, and as soon you complete all the fields click one of two button's options: "Send as Text" or "Send via Phone Call" to receive the confirmation code (the best fits you). Once you receive the code, fill the field "Confirmation Code" with it and click the Register button. If everything goes fine, click Done to complete the registration.

Figure 2. Modal to accept the platform and privacy policy.

After you have finished the registration, you'll be redirected to the QuickStarts page. Once there, select the platform you want to work with, Android in our case and, in the next screen, give a name to our app (mrbool-tests, for example). Then, click "Create New Facebook App ID" button and, in the next screen, select the Category of the new app, clicking in "Create App ID" button in the end, just as we see in Figure 3.

Figure 3. Creating a new Facebook App ID.

Generating key hashes

Now we have to fill in a field called Key Hashes.This field is precisely the signature of our project. We will have to generate it from the *.keystore file, so we will have to download the OpenSSL used to generate this signature. You can acquire it by direct download through the URL available at Links section or just downloading and installing the JDK (Java Developer Kit) that already comes with keytool inside (both options need to have the /bin folder added to Path System Variable as well in order to enable command line execution via prompt cmd).

To generate the key we need, just run the following command:

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

Note:You must have Android SDK (latest version) and Android Studio IDE (latest version) already installed in your machine in order to proceed with this tutorial.

Copy the key generated and save it for future use. Now, let's create our app at Android Studio IDE (you can use Eclipse ADT for same purposes as well, but some of the steps are very different and you may face some problems going this way). So, click "Start a new Android Studio project", give it an Application name (MrboolTests) and a Company Domain (com.mrbool.test), select the Project location and, then, click Next button. Next screen, leave all the options with their default values and click Next again. In the next screen we're going to choose the template of our app. So, select "Blank Activity" option and click Next button. Finally, fill the fields with the first blank activity info, as we see in Figure 4. Once you complete, click Finish button and wait until Android Studio creates the app and set up all the dependencies.

Figure 4. Creating a new app in Android Studio.

Now we can import the Facebook Android SDK necessary to develop with the Java classes of its dependency. For that, open the file build.gradle (into Gradle Scripts section) and add the following line of code before dependencies declaration, in order to get all the dependencies loaded from the Maven Central repository:

repositories { mavenCentral() }

Then, inside the dependencies declaration, add this line of code in the end:

compile ''

This will force Gradle to download the most recent Facebook Android SDK version and will add to our project classpath as well. Now, we can access its Java classes freely.

Now, get back to Facebook Developers page and, still in QuickStart page, in the end of it (section "Tell us about your Android project") inform the Package Name and Default Activity Classe Name, just as we did in Figure 5.

Figure 5. Setting up project properties.

After that, possibly you'll receive a popup asking if the package's name is right, once we did not publish it to the Google Play yet, because Facebook will search for this package id there. So, just click "Use this package name" button and you'll be prompted to inform the key hashes you've already generated before. Then, paste the key copied in the command line prompt, just inside the "Development Key Hashes" field and click Next. And that's it. Now you can start programming the code to test this library (go to the top of the page and click "Skip QuickStart").

Note: Sometimes Facebook doesn't add the key hash for Android specific purposes and we need to assure that this will be ok. So, access the app and, in the left side menu, click "Settings" option and check if the field "Key Hashes" is filled. If not, fill it with the right key hash.

Implementing the source code of the app

Firstly, it's necessary to add the App ID of our Facebook App to our code. Since we can need this info in many places around the code, it's a good idea to declare it into the strings.xml file, so this way we centralize it. So, open this file under the folder res/values/ and include this new string line:

<string name="facebook_app_id">417194965158475</string>

Remember that we have to change the id for yours. You can find it in the same left panel menu, Settings. Under the tab with the "Basic" title.

Before we move on, we need to declare the right permission of internet in the AndroidManifest.xml file at the Android project, as well as for the permission for reading external files (the images of the app test). Also, we need to add some extra Facebook configurations like the App Id we stored at strings.xml, the FacebookActivity and a Content Provider with the same ID. So, open this file and make it similiar to the one shown in Listing 1.

Listing 1. Giving internet permission to the project.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

            android:value="@string/facebook_app_id" />

            android:exported="true" />


Then we must define the XML code of our initial screen, ie, the screen that will be responsible for posting something in the Facebook's user page like a text or an image. So, change the content of the content_facebook.xml file to the code shown in Listing 2, and the file activity_facebook.xml to the one shown in Listing 3.

Listing 2. Code of the file content_facebook.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""



                android:text="What's on your mind?"
                android:textAppearance="?android:attr/textAppearanceLarge" />

                android:hint="Say something to your friends..."
                android:lines="4" />

                android:hint="URL of the website" />

                android:src="@drawable/image_not_found" />


                    android:text="Search Image" />

                    android:text="Post" />


Listing 3. Content of activity_facebook.xml.

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""


            app:popupTheme="@style/AppTheme.PopupOverlay" />


    <include layout="@layout/content_facebook" />


Open the emulator and run the app, and you'll see the screen shown in Figure 6. See that we're using the feature of templating in Android, for more details you can refer to the official documentation.

Figure 6. Initial screen of our Android app.

Now, let's go to our FacebookActivity code. Change the code precreated for the one presented in the Listing 4.

Listing 4. Code of our FacebookActivity class.


import android.content.Intent;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.share.ShareApi;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;

import java.util.Arrays;
import java.util.List;

public class FacebookActivity extends AppCompatActivity {

    private static final int ACTION_PICK_IMAGE = 1;

    private CallbackManager callbackManager;
    private LoginManager manager;
    private ImageView imgTest;
    private EditText edtURL;
    private EditText edtSaySmth;
    private Bitmap thePic;

    protected void onCreate(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(;
        toolbar.setTitle("Facebook Test");

        imgTest = (ImageView) findViewById(;
        edtURL = (EditText) findViewById(;
        edtSaySmth = (EditText) findViewById(;

        callbackManager = CallbackManager.Factory.create();

        List<String> permissionNeeds = Arrays.asList("publish_actions");

        manager = LoginManager.getInstance();
        manager.logInWithPublishPermissions(this, permissionNeeds);
        manager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            public void onSuccess(LoginResult loginResult) {
                Toast.makeText(FacebookActivity.this, "Facebook login success!", Toast.LENGTH_SHORT).show();

            public void onCancel() {
                Toast.makeText(FacebookActivity.this, "Facebook login canceled!", Toast.LENGTH_SHORT).show();

            public void onError(FacebookException exception) {
                Toast.makeText(FacebookActivity.this, "Facebook login error: " + exception.getMessage(), Toast.LENGTH_SHORT).show();

    public void updateStatusClick(View view) {
        String text = edtSaySmth.getText().toString();
        String url = edtURL.getText().toString();

        SharePhoto photo = new SharePhoto.Builder()

        SharePhotoContent content = new SharePhotoContent.Builder()

        ShareApi.share(content, null);
        Toast.makeText(FacebookActivity.this, "Picture posted with success on Facebook!", Toast.LENGTH_SHORT).show();

    public void loadImage(View view) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);

        startActivityForResult(photoPickerIntent, ACTION_PICK_IMAGE);

    protected void onActivityResult(int requestCode, int responseCode, Intent data) {
        super.onActivityResult(requestCode, responseCode, data);
        if (requestCode == ACTION_PICK_IMAGE) {
            if (responseCode == RESULT_OK && data != null) {
                Uri selectedImage = data.getData();
                try {
                    thePic = getBitmapFromUri(selectedImage);
                } catch (IOException e) {
        callbackManager.onActivityResult(requestCode, responseCode, data);

    private Bitmap getBitmapFromUri(Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        return image;


Let's take a look at the methods created:

  • onCreate(): initializes the toolbar component (and its title), set the content view (activity_facebook.xml), and initializes the ImageView to display the image selected, and both EditText's to get the message text and the URL, respectively. Note how we initialize the FacebookSdk API through sdkInitialize() method passing the context as argument. Then, we create a new CallbackManager, a class from Facebook SDK API that enables us to login the user and analysis when the events of success, cancel or error happen. Also, to login with some specific permissions, we need to pass them as a string array with the correct keys of each one, in our case we're gonna use just the permission that allows to publish things (text, links, images, etc.). LoginManager class is the responsible to provide us all the necessary methods.
  • updateStatusClick(): called when POST button is clicked. It'll be responsible for getting both texts from EditText's widgets, creating the SharePhoto and SharePhotoContent objects, that we'll use to set all the params, including the picture selected.
  • loadImage(): creates a new Intent to select one image from our local/external storage and call the onActivityResult() method to handle it.
  • onActivityResult(): we first test if the result is ok and the action is to pick an image and, then, get its data (URI), passing it to the getBitmapFromUri() method that will convert to Bitmap format.
  • getBitmapFromUri(): converts the URI to a Bitmap object.

That's it, we have our code complete. Now, let's go to test it. Run the project in your Android device and the first screen will be to authenticate yourself. So, do it and you'll be redirected to the authorization page, showing that the Facebook App will access your personal information; click OK like in Figure 7. Next, you'll be prompted to enable Facebook App to post on your Facebook timeline, so select the right group of permission and click OK again.

Figure 7. Enabling access to personal information.

Once you did that, you're already logged in Facebook. So, type some text into the fields and a right URL, and click "Search Image" button, select an image and you'll see same result as in Figure 8. Then, click "Post" button. Go to your Facebook timeline and you'll see something like is shown in Figure 9.

Figure 8. Filling all the fields in the screen.

Figure 9. Checking the final result in personal Facebook timeline.


That's it. All you need to know about how to post things on Facebook through your own Android app. The steps are, of course, different from each mobile platform, but the main principles we can already understand and use for your programming life. Now, test some other things, like login auth, posting a video, link, and other things via API. Good luck!


Facebook Developers Page:

OpenSSL for Windows:

Diogo Souza works as Java Developer at Fulcrum Worldwide and has worked for companies such as Indra Company, Atlantic Institute and Ebix LA. He is also an Android trainer, speaker at events on Java and mobile world and a DevMedia ...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login