Visit Sponsor

Written by 4:50 pm Android

Using Facebook SDK in Android – Integration Guide

Overview

The Facebook SDK for Android enables developers to integrate Facebook services such as authentication (Facebook Login), social sharing, graph API access, and app analytics into Android applications. This documentation explains how to set up the Facebook SDK, configure your Android project, implement Facebook Login, and handle basic interactions with the Facebook platform.

Prerequisites

Before integrating the Facebook SDK:

  • Ensure you have Android Studio installed
  • Your app must have a valid package name and Android signature
  • Create a Facebook Developer account
  • Register your Android app in the Facebook Developer Console

The integration covers a typical use case: authenticating users using Facebook credentials.

Step 1: Create a Facebook App

  1. Go to Facebook Developers → My Apps → Add a New App
  2. Choose Consumer and click Next
  3. Provide a Display Name and Contact Email
  4. After creation, select Android as the platform
  5. Enter your package name and default activity class (e.g., com.example.app.MainActivity)
  6. Add your key hashes (generated via keytool) to the app settings

Registering your app ensures that Facebook recognizes and allows API calls from your Android application.

Step 2: Add Facebook SDK Dependencies

Add the Facebook SDK to your project via Gradle.

In the project’s build.gradle (project level), ensure you have:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
}

In the app module’s build.gradle:

dependencies {
    implementation 'com.facebook.android:facebook-login:latest.release'
}

Replace latest.release with the most recent stable version from the Facebook SDK Maven repository.

Step 3: Configure AndroidManifest.xml

Add the necessary permissions and metadata to your AndroidManifest.xml:

<manifest ...>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application ...>
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>
        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"/>
        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider{APP_ID}"
            android:exported="true"/>
    </application>
</manifest>

Add the facebook_app_id string to res/values/strings.xml:

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

Step 4: Initialize the Facebook SDK

Initialize the SDK in your application class:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
    }
}

Register this class in the AndroidManifest.xml within the <application> tag:

<application
    android:name=".MyApplication"
    ...>

Step 5: Implement Facebook Login

Add Login Button in Layout

In your activity layout XML:

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"/>

Handle Login in Activity

In your activity class:

public class MainActivity extends AppCompatActivity {

    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        callbackManager = CallbackManager.Factory.create();

        LoginButton loginButton = findViewById(R.id.login_button);
        loginButton.setPermissions(Arrays.asList("email", "public_profile"));

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // Handle successful login
            }

            @Override
            public void onCancel() {
                // Handle login cancellation
            }

            @Override
            public void onError(FacebookException error) {
                // Handle login error
            }
        });
    }

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

This setup handles authentication flow and callbacks.

Step 6: Fetch User Profile Data

Once logged in, you can access profile data via the Graph API:

GraphRequest request = GraphRequest.newMeRequest(
    AccessToken.getCurrentAccessToken(),
    (object, response) -> {
        try {
            String name = object.getString("name");
            String email = object.getString("email");
            // Handle additional fields
        } catch (JSONException e) {
            e.printStackTrace();
        }
    });

Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();

This retrieves key profile fields. Adjust permissions and fields as needed.

Common Integration Scenarios

Logout

LoginManager.getInstance().logOut();

Access Token Usage

Use AccessToken.getCurrentAccessToken() for session logic and server communication.

Security and Privacy Considerations

  • Request only the permissions needed for your use case
  • Always handle canceled or failed login paths
  • Respect user privacy and avoid storing sensitive data without consent
  • Use HTTPS for server-side verification of Facebook tokens
Visited 10 times, 1 visit(s) today
Close