Get Started – Android

This guide shows you how to add App Events to your new or existing app by integrating the Facebook SDK then logging these events.

Before You Start

You will need:

Step 1: Configure Your Facebook App

Go to the App Dashboard, click My Apps, and create a new app if you don't already have one. Navigate to Settings > Basic to view the App Details Panel with your App ID, your App Secret, and other details about your app.

Set up your app for advertising by adding the following details:

  • App Domains - Provide Google Play Store URL of your app.
  • Privacy Policy URL - Provide a Privacy Policy URL. Required to take your app public.
  • Terms of Service URL - Provide a Terms of Service URL.
  • Platform - Scroll to the bottom of the Settings panel to add the Android Platform. Add the follow details of your app:

Save your changes.

To learn more about adding details to your app, such as an icon or category, visit the App Development docs.

Step 2: Link Your Facebook Ad Account with Your App

To run ads and measure installs in the Ads Manager, you are required to associate at least one Ad Account with your app.

  1. In the app dashboard click Settings > Advanced.
  2. In Authorized Ad Account IDs, add your Ad Account IDs. You can get your ad account IDs from your Ads Manager.
  3. If you also have a business account, in Authorized Businesses, add your Business Manager ID. You can find your Business Manager ID in the URL of your Business Manager.

Step 3: Integrate the Facebook SDK in Your Android App

To add the Facebook SDK to a project, add the SDK as a build dependency. You will also need to specify your app ID.

If you're adding the SDK to an existing project, start at step 3.

  1. Go to Android Studio | Start a new Android Studio project | Application name | Minimum SDK.
  2. Select API 15: Android 4.0.3 9 (IceCreamSandwich) or higher and click Next.
  3. Click Basic Activity and then click Next, and then Finish.
  4. In your project, open <your_app> | Gradle Scripts | build.gradle (Project) and add the following to the buildscript { repositories {}} section to download the SDK from the Maven Central Repository:
    mavenCentral()
  5. In your project, open <your_app> | Gradle Scripts | build.gradle (Module: app) and add the following to the dependencies{} section to compile the latest version of the SDK:
    implementation 'com.facebook.android:facebook-android-sdk:[5,6)'
    
  6. Open your /app/res/values/strings.xml file and add the following lines (remember to replace [APP_ID] with your actual app ID):
    <string name="facebook_app_id">[APP_ID]</string>
    <string name="fb_login_protocol_scheme">fb[APP_ID]</string>
    
  7. In the app/manifests/AndroidManifest.xml file, add a meta-data element to the application element:
    <application android:label="@string/app_name" ...>
        ...
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
        ...
    </application>
    
  8. Open the /app/manifest/AndroidManifest.xml file and add the following uses-permission element after the application element:
    <uses-permission android:name="android.permission.INTERNET"/>
  9. Build your project.

Step 4: Add App Events

There are three ways events are tracked in your app:

Automatically Logged Events

When you use the Facebook SDK, certain events in your app are automatically logged and collected for Facebook Analytics unless you disable automatic event logging. These events are relevant for all use cases - targeting, measurement and optimization. There are three key events collected as part of the Automatic App Event Logging: App Install, App Launch, and Purchase. When automatic logging is enabled, advertisers are able to disable these events, as well as other Facebook internal events such as login impression events. However, if you have disabled automatic logging, but still want to log specific events, such as install or purchase events, manually implement logging for these events in your app.

EventDetails

App Install

The first time a new person activates your app or the first time your app starts on a particular device.

App Launch

When a person launches your app, the Facebook SDK is initialized and the event is logged. However, if a second app launch event occurs within 60 seconds of the first, the second app launch event is not logged.

For the Facebook SDK for Android v4.18, and earlier, SDK initialization is a manual process that differs from the manual event logging process described in this doc. Please upgrade to the latest SDK version or scroll to the Legacy SDK Initialization section to add events manually.

In-App Purchase

When a purchase processed by Google Play has been completed. If you use other payments platforms, add purchase event code manually.

In-app purchase logging is automatically enabled for apps that have installed or upgraded to v4.39. For apps running an earlier version, enable in-app purchase events in Basic > Settings Android card in the app dashboard or add the purchase event code manually.

Facebook SDK Crash Report

(For Facebook Use Only.)

If your app crashed due to the Facebook SDK, a crash report is generated and sent to Facebook when your app is restarted. This report contains no user data and helps Facebook ensure the quality and stability of the SDK. To opt out of logging this event, disable automatically logged events.

Disable Automatically Logged Events

To disable automatically logged events add the following to your AndroidManifest.xml file:

<application>
  ...
  <meta-data android:name="com.facebook.sdk.AutoLogAppEventsEnabled"
           android:value="false"/>
  ...
</application>

In some cases, you want to delay the collection of automatically logged events, such as to obtain user consent or fulfill legal obligations, instead of disabling it. In this case, call the setAutoLogAppEventsEnabled() method of the FacebookSDK class and set to true to re-enable event logging after the end-user provides consent.

setAutoLogAppEventsEnabled(true);

To suspend logging again for any reason, set the setAutoLogAppEventsEnabled() method to false.

setAutoLogAppEventsEnabled(false);

You can also disable automatic In-App Purchase event logging using the app dashboard. Go to the Android card under Basic > Settings and toggle the switch to No.

Disable Automatic SDK Initialization

To disable automatic SDK initialization, add the following to your AndroidManifest.xml file:

<application>
  ...
  <meta-data android:name="com.facebook.sdk.AutoInitEnabled"
           android:value="false"/>
  ...
</application>

In some cases, you want to delay the SDK initialization, such as to obtain user consent or fulfill legal obligations, instead of disabling it. In this case, call the class method setAutoInitEnabled and set it to true to manually initialize the SDK after the end-user provides consent.

FacebookSdk.setAutoInitEnabled(true)
FacebookSdk.fullyInitialize()

Disable Collection of Advertiser IDs

To disable collection of advertiser-id, add the following to your AndroidManifest.xml file:

<application>
  ...
  <meta-data android:name="com.facebook.sdk.AdvertiserIDCollectionEnabled"
           android:value="false"/>
  ...
</application>

In some cases, you want to delay the collection of advertiser_id, such as to obtain User consent or fulfill legal obligations, instead of disabling it. In this case, call the setAdvertiserIDCollectionEnabled() method of the FacebookSDK class and set it to true to re-enable collection of advertiser_id after the end-user provides consent.

setAdvertiserIDCollectionEnabled(true);

To suspend collection for any reason, set the setAdvertiserIDCollectionEnabled() method to false.

setAdvertiserIDCollectionEnabled(false);

Manually Log Events

Create an AppEventsLogger object using the helper methods to log your events, where this is the Activity your method is in.

AppEventsLogger logger = AppEventsLogger.newLogger(this);

You can then log your event to logger, where AppEventConstants.EVENT_NAME_X is one of the constants shown in the Standard Events table or from the Code Generator code.

logger.logEvent(AppEventsConstants.EVENT_NAME_X);

You can also specify a set of parameters in a Bundle and a valueToSum property which is an arbitrary number that can represent any value, for example, a price or a quantity. When reported, all of the valueToSum properties are summed together. For example, if 10 people purchased one item and each item cost $10 (and passed in valueToSum) then they would be added together to report $100.

Note, both valueToSum and parameters are optional.

Bundle params = new Bundle();
params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "product");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, "[{\"id\": \"1234\", \"quantity\": 2}, {\"id\": \"5678\", \"quantity\": 1}]");

logger.logEvent(AppEventsConstants.EVENT_NAME_PURCHASE,
                54.23,
                params);
Bundle params = new Bundle();
params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "product");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, "HDFU-8452");

logger.logEvent(AppEventsConstants.EVENT_NAME_ADDED_TO_CART,
                54.23,
                params);

Get Code

Use the Code Generator to get code for standard events or custom events, and parameters.

To Generate Code for a Standard or Custom Event

  1. Choose the tab of the type of event code you want, Standard Event or Custom Event.
  2. In Event Name, enter the name of your event.
  3. Click Add Event Paramater if you would like to add parameters to your custom event.
  4. Click Get Code.
  5. In the window, select a language to get the code to copy and paste into your app.

To log a custom event, just pass the name of the event as a string. This function assumes that logger is an instance of AppEventsLogger and has been created using AppEventsLogger.newLogger() call.

public void logBattleTheMonsterEvent () {
    logger.logEvent("BattleTheMonster");
}

Event Parameters

Each event can be logged with a valueToSum and a set of up to 25 parameters. They are passed via a Bundle where the key holds the parameter name and the value either a String or an int. If you provide another type of value that is not compliant such as a boolean, the SDK logs a warning to LogginBehavior.APP_EVENT.

Refer to the Standard Event Parameters Reference guide for parameters typically used with standard events. These parameters are intended to provide guidance, however, you can provide your own parameters as well. Your app should log parameters that you are interested in seeing breakdowns for in insights.

Do not use "event" as the name of a parameter. Custom parameters with the name "event" will not be logged. Use another name or add a prefix or suffix to the name, such as my_custom_event.

Legacy SDK Initialization

It is strongly recommended that you upgrade to the latest SDK version.

In the Facebook Android SDK v4.18 and earlier, the SDK must be initialized and app activation events logged explicitly. The SDK provides a helper method to log the app activation event. To do this, invoke the SDK's app activation helper once when the application is created. The following code demonstrates how to initialize the SDK and log the app activation event in the Application class:

package com.example.hellofacebook;

import android.app.Application;

import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;

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

Step 5: Test Your Event Logging

The App Ads Helper allows you to test the app events in your app to ensure that your app is sending events to Facebook.

  1. Open the App Ads Helper.
  2. In Select an App, choose your app and choose Submit.
  3. Go to the bottom and choose Test App Events.
  4. Start your app and send an event. The event appears on the web page.

Enabling Debug Logs

Enable debug logs to verify App Event usage from the client side. The debug logs contain detailed requests and JSON responses. Enable debug logs by adding the following code after initializing the Facebook Android SDK:

FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS);

This is only for debugging purposes. Please disable debug logs before deploying your app to the public.

Learn More

For more information and helpful hints on App Events check out:

Example Apps

We have created some examples for different app types to show you how you can use app events. Each of the example apps provides a screen by screen breakdown of the different events with code examples. It is important to note that these examples are a starting point for your app and should be customized by you.