Messenger SDK for Android

Send images, animated gifs, videos and audio clips to Messenger from your Android app

Implementation in Android

APIs to integrate with Messenger are included in the Facebook SDK for Android. Integration is also possible without the SDK, by passing an Intent to the Messenger Activity. However, we highly recommend you use the SDK.

The SDK includes convenient functions for basic and optimized integrations. In addition, the SDK also contains Messenger-branded buttons and a sample application to help get you started.

Also, be sure to integrate analytics so you can obtain relevant metrics for your application.

Prerequisites

Step 1: Get a Facebook App ID

In order to integrate with Messenger for Android, you will need a Facebook App ID. If you don't already have one, create one here.

Step 2: Add the SDK to your project

The Messenger SDK for Android is a component of the Facebook SDK for Android. To use the Facebook Places SDK in your project, make it a dependency in Maven, or download it. Choose the method you prefer with the following button.

Link the SDK with Maven

  1. In your project, open your_app | Gradle Scripts | build.gradle (Project) and add the following repository to the buildscript { repositories {}} section to download the SDK from the Maven Central Repository:
    mavenCentral() 
  2. In your project, open your_app | Gradle Scripts | build.gradle (Module: app) and add the following compile statement to the dependencies{} section to compile the latest version of the SDK:
    compile 'com.facebook.android:facebook-messenger:[4,5)'
  3. Build your project.

Download the SDK

To download the SDK, click the following button.

Download SDK

When you use the Facebook Messenger SDK, events in your app are automatically logged and collected for Facebook Analytics unless you disable automatic event logging. For details about what information is collected and how to disable automatic event logging, see Automatic App Event Logging.

Step 3: Configure your project

You'll need to make sure your project is properly configured for Messenger integration. Your app ID should be in your AndroidManifest.xml file:

<application android:label="@string/app_name">

    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

</application>

In addition, you'l also need to add the following entry to your strings.xml file:

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

Make sure your Package Name, Class Name and Key Hashes are properly set, and match the entries in your app's Facebook developer page:

Apps that are incorrectly configured may encounter errors when sharing to Messenger. Content may not display attribution, or fail to send entirely. You can use Android's System Log to see detailed error information that will help you debug any issues.

Step 4: Import MessengerUtil classes

In order to use Messenger integration in the Facebook SDK, make sure you have the following import statements in your Activity class that shares content into Messenger:

import com.facebook.messenger.MessengerUtils;
import com.facebook.messenger.MessengerThreadParams;
import com.facebook.messenger.ShareToMessengerParams;

Step 5: Setup your test users

Be sure that the users you are testing with have a role in your Facebook app. This is set in App Settings in the Roles section. If your app is in Development Mode, the buttons under the content will only appear to users who have a role (Administrators, Developers, and Testers) in your Facebook app .

Basic integration

Sharing content

With Messenger integration, you can share images, videos, animated gifs, and audio clips. You can use the Facebook SDK or share directly through Intents. We highly recommend using the SDK, as it provides a convenient API and handles edge cases such as different versions of Messenger, as well as Messenger being absent on a phone, correctly.

The sample code below illustrates usage of MessengerUtils to share an image (a jpeg, in this case) to Messenger:

String mimeType = "image/jpeg";

// contentUri points to the content being shared to Messenger
ShareToMessengerParams shareToMessengerParams =
        ShareToMessengerParams.newBuilder(contentUri, mimeType)
                .build();

// Sharing from an Activity
MessengerUtils.shareToMessenger(
       this,
       REQUEST_CODE_SHARE_TO_MESSENGER,
       shareToMessengerParams);

You can also share content through Intent without using the SDK.

Supported content types

Messenger supports the following mime types:

Format Mime Type Notes

JPEG

image/jpeg

--

GIF

image/gif

--

PNG

image/png

Transparency is not supported.

WebP

image/webp

--

MP4

video/mp4

Recommended format is H.264 with baseline profile for video and AAC for audio. The video should be a format that is playable on the phone using its native decoder.

MP3

audio/mpeg

--

Additional parameters

If you're supporting optimized integration, you can send extra metadata that contains information about the content being shared. For example, you can store a serialized JSON string, which your app will be able to acces in the Reply flow on the receiver's device - if a person taps "Reply" on content with metadata, this information will be relayed back to your app.

In order to add metadata to your content, add it to the ShareToMessengerParams:

String metadata = "{ \"image\" : \"trees\" }";
ShareToMessengerParams shareToMessengerParams =
        ShareToMessengerParams.newBuilder(contentUri, "image/jpeg")
                .setMetaData(metadata)
                .build();

You can also set metadata through the Intent without using the SDK. Finally, make sure to read the best practices section for tips on how best to use metadata.

Using Messenger Buttons

The Messenger SDK includes assets for Messenger-themed buttons. These buttons are available in blue and white, and in rectangular or circular shapes. The layouts for these buttons are available under /res/layout/:

  • messenger_button_send_blue_small.xml
  • messenger_button_send_blue_large.xml
  • messenger_button_send_blue_round.xml
  • messenger_button_send_white_small.xml
  • messenger_button_send_white_large.xml
  • messenger_button_send_white_round.xml

You can use an include tag to place a Messenger button in your layout:

<LinearLayout>
  <!-- Include this in your layout -->
  <include layout="@layout/messenger_button_send_blue_large" />    

</LinearLayout>

What if Messenger isn't installed?

It's possible for a person to have your app, but not Messenger, installed on their phone. In this case, your app should redirect people to the Google Play Store's Messenger page for installation when they try to share content to Messenger. The MessengerUtil class handles this for you automatically. You can follow these steps to enable this manually, if you're not using the SDK.

Optimized integration

App can integrate more deeply to enable options for discovery and engagement. In addition, apps approved for optimized sharing may also be featured in the composer to help discovery.

Read more about the different levels of integration.

Handling calls from Messenger

Messenger may call into your app in two different situations - through the "Reply" button under attributed content, or through the composer tab. In order to handle these calls, add the following IntentFilter for an Activity in your AndroidManifest.xml:

<activity ...>

  <intent-filter>
      <action android:name="android.intent.action.PICK"/>
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="com.facebook.orca.category.PLATFORM_THREAD_20150314" />
  </intent-filter>

</activity>

Messenger will start the Activity tied to the IntentFilter with a call to startActivityForResult, and you should create and send the content back to Messenger from this Activity.

Save the state so that you know you know you came in through this flow. We're using a boolean mPicking.

// Are we in a PICK flow?
private boolean mPicking;

Intent intent = getIntent();

if (Intent.ACTION_PICK.equals(intent.getAction())) {
    mPicking = true;    
    MessengerThreadParams mThreadParams = MessengerUtils.getMessengerThreadParamsForIntent(intent);
    
    String metadata = mThreadParams.metadata;
    List<String> participantIds = mThreadParams.participants;
}

Sending content back to Messenger

After the person creates their content, call the following to send it back to Messenger. Note that we call finishShareToMessenger if mPicking is true, otherwise we call shareToMessenger.

ShareToMessengerParams shareToMessengerParams =
    ShareToMessengerParams.newBuilder(contentUri, "image/jpeg")
        .setMetaData("{ \"image\" : \"trees\" }")
        .build();

if (mPicking) {
    MessengerUtils.finishShareToMessenger(this, shareToMessengerParams);
} else {  
    MessengerUtils.shareToMessenger(
        this,
        REQUEST_CODE_SHARE_TO_MESSENGER,
        shareToMessengerParams);
}

You can also send content back to Messenger using Intent without using the SDK.

Accessing metadata and participant user IDs

When your app shares content into Messenger, it may have set extra metadata. When Messenger calls back to your app (through the reply or compose flows), this information is passed back to you.

In addition, you may also get access to the user ids of the participants in the thread during the reply flow. This can be used to create personalized experiences for people in a conversation. You will only receive user ids of people who have allowed personalized replies and are logged into Facebook in your app. Before passing participant ids back to your application, we present the following dialog to people:

In order to obtain either metadata or thread participants, note the following lines above to retrieve this data from the Intent:

MessengerThreadParams mThreadParams = MessengerUtils.getMessengerThreadParamsForIntent(intent);

String metadata = mThreadParams.metadata;
List<String> participantIds = mThreadParams.participants;

You can also access metadata and user IDs from Intent without using the SDK. Finally, make sure to read up on our best practices for using Login to create personalized experiences.

Analytics

When doing an optimized integration, you must also track app activations using analytics.

Integration through Intents

You can integrate with Messenger without the SDK by using Intents. This section contains information on how to accomplish the functionality above without using utility functions, and can be skipped if you're using the SDK.

Basic integration

Sharing content

To share a piece of content into Messenger, simply call startActivityForResult with a specially-crafted Intent:

private static final String EXTRA_PROTOCOL_VERSION = "com.facebook.orca.extra.PROTOCOL_VERSION";
private static final String EXTRA_APP_ID = "com.facebook.orca.extra.APPLICATION_ID";
private static final int PROTOCOL_VERSION = 20150314;
private static final String YOUR_APP_ID = "[YOUR_FACEBOOK_APP_ID]";
private static final int SHARE_TO_MESSENGER_REQUEST_CODE = 1;

...

String mimeType = "image/*";

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setPackage("com.facebook.orca");
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
intent.putExtra(EXTRA_PROTOCOL_VERSION, PROTOCOL_VERSION);
intent.putExtra(EXTRA_APP_ID, YOUR_APP_ID);

activity.startActivityForResult(shareIntent, SHARE_TO_MESSENGER_REQUEST_CODE);

Note that, although Messenger does not currently return a result to the calling app, you must use Activity.startActivityForResult instead of Activity.startActivity.

Additional parameters

You can pass metadata through intent-based sharing by adding the following Extra:

private static final String EXTRA_METADATA = "com.facebook.orca.extra.METADATA";
    
...

String metadata = "{ \"image\" : \"trees\" }";
intent.putExtra(EXTRA_METADATA, metadata);

Optimized integration

Send content back to Messenger

When people tap on the "Reply" button, or access your app through the composer in Messenger, an Activity in your app will be called, through the IntentFilter discussed above. To send the reply content back into Messenger, you must build a reply intent, and pass it back to Messenger with a call to setResult (typically followed by a call to finish to complete your Activity's lifecycle). We provide a basic example of this functionality below:

private static final String EXTRA_PROTOCOL_VERSION = "com.facebook.orca.extra.PROTOCOL_VERSION";
private static final String EXTRA_APP_ID = "com.facebook.orca.extra.APPLICATION_ID";
private static final String EXTRA_IS_COMPOSE = "com.facebook.orca.extra.IS_COMPOSE";
private static final String EXTRA_IS_REPLY = "com.facebook.orca.extra.IS_REPLY";
private static final String EXTRA_THREAD_TOKEN = "com.facebook.orca.extra.THREAD_TOKEN";
private static final String YOUR_APP_ID = "1234567890";

private boolean isReply, isCompose;
private String threadToken;

...

Intent intent = getIntent();
Bundle appLinksBundle = intent.getBundleExtra("al_applink_data");

if (appLinksBundle != null) {
  Bundle extras = appLinksBundle.getBundle("extras");

  isCompose = extras.getBoolean(EXTRA_IS_COMPOSE, false);
  isReply = extras.getBoolean(EXTRA_IS_REPLY, false);
  threadToken = extras.getString(EXTRA_THREAD_TOKEN);
}

...

if (isCompose || isReply) {  
  // In the composer or reply flow
  Intent result = new Intent(Intent.ACTION_SEND);

  // contentUri points to the content being shared to Messenger
  // mimeType defines the type of content we're sharing
  result.setDataAndType(contentUri, mimeType);
  result.setPackage("com.facebook.orca");
  result.putExtra(EXTRA_PROTOCOL_VERSION, PROTOCOL_VERSION);
  result.putExtra(EXTRA_APP_ID, YOUR_APP_ID);

  // This is important
  result.putExtra(EXTRA_THREAD_TOKEN, threadToken);

  setResult(Activity.RESULT_OK, result);
  finish();
}

Notice how most of the structure of the reply Intent is the same as in the initial share flow (both the protocol version, and app id, are required fields). However, unlike in the initial share flow, for the reply you must specify your content's Uri in the Intent's data, rather than in the EXTRA_STREAM field.

Accessing metadata and participant user IDs

The metadata string, and the list of participant IDs, is available as an extra in the Intent Messenger passes into your application. The participant IDs are a String containing a comma-separated list of participant IDs:

private static final String EXTRA_METADATA = "com.facebook.orca.extra.METADATA";
private static final String EXTRA_PARTICIPANTS = "com.facebook.orca.extra.EXTRA_PARTICIPANTS";

...

Intent intent = getIntent();
Bundle appLinksBundle = intent.getBundleExtra("al_applink_data");

if (appLinksBundle != null) {
  Bundle extras = appLinksBundle.getBundle("extras");
  String metadata = extras.getString(EXTRA_METADATA);
    String participantIDs = extras.getString(EXTRA_PARTICIPANTS);
}

Handling when Messenger isn't installed

The Messenger SDK contains functionality that redirects people to the Google Play Store in the case where Messenger isn't installed on a phone. Below is sample code for implementing that functionality directly:

public static final String PACKAGE_NAME = "com.facebook.orca";

public static void myShareFunction() {

  if (!hasMessengerInstalled(activity)) {
    openMessengerInPlayStore(activity);
    return;
  }
...
}

public boolean hasMessengerInstalled(Context context) {
  try {
    context.getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
    return true;
  } catch (PackageManager.NameNotFoundException e) {
    return false;
  }
}

public void openMessengerInPlayStore(Context context) {
  try {
    startViewUri(context, "market://details?id=" + PACKAGE_NAME);
  } catch (ActivityNotFoundException anfe) {
    startViewUri(context, "http://play.google.com/store/apps/details?id=" + PACKAGE_NAME);
  }
}

private void startViewUri(Context context, String uri) {
  context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
}

Sample App

The Messenger SDK includes a complete sample application that implements all aspects of Messenger integration - content sharing, the reply and composer flows, as well as using metadata and thread participants. Make sure to check it out for help getting your integration setup. The sample app is located in /samples/MessengerSendSample.

Technical Best Practices

These best practices only apply to optimized integrations.

Design metadata for multiple versions

Consider how you structure your metadata. If you ship successive versions of your app, they might coexist, and communicate with each other. Future-proof your app by using data in a way that's forward and backward compatible. For example, you could use a JSON structure for storing information and include a version tag to know which fields it contains.

Handle send flow vs reply flow

When using shareToMessenger, the person enters a flow in Messenger where they can select recipients for your app's content. When using finishShareToMessenger, they enter a flow where the content is rendered inline within an existing conversation. When your app is called via Messenger, you should use finishShareToMessenger to ensure seamless integration.

Use Facebook Login to create personalized experiences

By integrating Login into your app, you can receive the user IDs of the people in a conversation. This enables you to create content personalized for that set of people. For example, if you're building a sports tracking app, you can show sticker packs containing rival teams of people in the conversation.

Analytics

In order to record metrics from your integration, call the following App Event, by making the calls below in your Activity:

import com.facebook.AppEventsLogger;

@Override
protected void onResume() { 
  super.onResume(); 
  AppEventsLogger.activateApp(this); 
}

@Override
protected void onPause() { 
  super.onPause(); 
  AppEventsLogger.deactivateApp(this);
}

You must integrate analytics and track app activations if you're submitting an optimized integration.


You can read more details about App Events in Android here.

Releasing your app

There are a few things to keep in mind as you prepare your app for release.

Attribution

When content is shared into Messenger, your app icon and name will appear under your content. This is your App Icon and Display Name in your app settings.

If your app is in Development Mode, attribution will only appear to users who have a role in your Facebook app (Administrators, Developers, and Testers). When your app is made public, attribution will appear for the general public.

Release key hash

When you build an app to publish, it's typically signed with a different key hash than the one you use in your development environment. Be sure to add this key hash to your Android app settings otherwise you may receive an error regarding key hashes. Read more about release key hashes.