Getting Started with App Events for Android

App Events is a feature of the Facebook SDK for Android that allows you to track actions within your app or website. Tracking these actions, or events, allows you to target, measure, and optimize the delivery of your ads to people most likely to take action. This guide shows you how to add App Events to your new or existing app by integrating the Facebook SDK then logging these events.

There are three types of App Events:

Requirements

If you already have implemented the Facebook Android SDK begin at Step 5. Set Your App Advertising Details.

1. Integrate the Facebook SDK in Your Android App

To add the Facebook SDK to a project, add the SDK as a build dependency.

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:[4,5)'
    
  6. 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>
    
    
  7. Build your project.

2. Add Your Facebook App ID

Create strings for your Facebook app ID and for those needed to enable Chrome Custom Tabs. Also, add FacebookActivity to your Android manifest.
  1. Open your /app/res/values/strings.xml file and add the following:
    <string name="facebook_app_id">[APP_ID]</string>
    <string name="fb_login_protocol_scheme">fb[APP_ID]</string>
    
  2. Open the /app/manifest/AndroidManifest.xml file and add the following user-permission element after the application element:
              
    <user-permission android:name="android.permission.INTERNET"/>
    
    

3. Add Your Development and Release Key Hashes

To ensure the authenticity of the interactions between your app and Facebook, you need to supply us with the Android key hash for your development environment. If your app has already been published, you should add your release key hash too.
Generating a Development Key Hash
You'll have a unique development key hash for each Android development environment.
Mac OS
To generate a development key hash, open a terminal window and run the following command:
      
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
Windows
You will need the following: To generate a development key hash, run the following command in a command prompt in the Java SDK folder:
      
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\USERNAME\.android\debug.keystore" | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" sha1 -binary | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" base64
      
This command will generate a 28-character key hash unique to your development environment. Copy and paste it into the field below. You will need to provide a development key hash for the development environment of each person who works on your app.
Generating a Release Key Hash
Android apps must be digitally signed with a release key before you can upload them to the store. To generate a hash of your release key, run the following command on Mac or Windows substituting your release key alias and the path to your keystore:
      
keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64
This will generate a 28-character string that you should copy and paste into the field below. Also, see the Android documentation for signing your apps.
Key Hashes

4. Tell Us about Your Android Project

If you have already set this in your app's dashboard Settings > Basic Android Card go to the next step.

Package Name
Your package name uniquely identifies your Android app. We use this to let people download your app from Google Play if they don't have it installed. You can find this in your Android Manifest or your app's build.gradle file.
Default Activity Class Name
This is the fully qualified class name of the activity that handles deep linking such as com.example.app.DeepLinkingActivity. We use this when we deep link into your app from the Facebook app. You can also find this in your Android Manifest.

5. Set Your App Advertising Details (Optional)

In your app dashboard, go to Settings > Basic to view the App Details panel with your App ID, your App Secret, etc. Add the following:

  • App Domains - Provide the Google Play URL of your app.
  • Platform - Scroll to the bottom of the Settings page to add the Android Platform.
  • Privacy Policy URL - You must provide a Privacy Policy URL. Must be provided to take your app public.
  • Terms of Service URL - You must provide a Terms of Service URL.
See the App Development docs to learn more about app details.

6. Link your Facebook Ad Account with your App (Optional)

To run ads and measure installs in the Ads Manager, you need 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

7. Add App Events

There are two ways to add events to your app.

Automatically Logged Events

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.

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 below. Please upgrade to the latest SDK version or scroll to the Legacy SDK Initialization section to manually add events.

In-App Purchase

When a purchase processed by Google Play has been completed. If you use other payments platforms, you will need to 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.

Disable Automatically Logged Events

There are two ways to disable automatic event logging of In-App Purchase events, using the app dashboard or programmatically.

To disable automatic event logging using the app dashboard go to Basic > Settings Android card and toggle the Log In-App Purchase Events Automatically switch to No.

To disable automatic event logging programmatically, add the following line to your AndroidManifest.xml file:

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

In some cases, you may wish 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, add the same code to your manifest:

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

Then re-enable auto-logging after an end-user provides consent, by calling the setAutoLogAppEventsEnabled() method of the FacebookSDK class.

setAutoLogAppEventsEnabled(true);

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

setAutoLogAppEventsEnabled(false);

Disable Collection of Advertiser IDs

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

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

In some cases, you may wish to delay the collection of advertiser_id, such as to obtain user consent or fulfill legal obligations, instead of disabling it. In this case, add the same code to your manifest:

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

Then, re-enable collection of advertiser_id after the end-user provides consent, by calling the setAdvertiserIDCollectionEnabled() method of the FacebookSDK class and set it to true.

setAdvertiserIDCollectionEnabled(true);

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

setAdvertiserIDCollectionEnabled(false);

Logging Events Manually

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 (e.g., a price or a quantity). When reported, all of the valueToSum properties will be 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, \"item_price\": 5.99}, {\"id\": \"5678\", \"quantity\": 1, \"item_price\": 9.99}]");

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);

Visit the Android SDK Reference Documentation for more information about the AppEventsLogger class and more.

Standard Events

Add standard events and parameters to your app. Use the Code Generator to get the code for these events.

To Generate Code for a Standard Event

  1. Choose the Standard Event tab.
  2. In Event Name, choose a standard event.
  3. Choose Get Code.
  4. In the window, select a language to see the code to copy and paste into your app.

Take a look at our Example Apps to view some scenarios of using App Events.

Standard Events

AppEventsConstants Value valueToSum Parameters

Achieved Level: EVENT_NAME_ACHIEVED_LEVEL

LEVEL

App Launched: EVENT_NAME_ACTIVATED_APP

Clicked on an Ad:
EVENT_NAME_AD_CLICK

AD_TYPE

Shown an Ad:
EVENT_NAME_AD_IMPRESSION

AD_TYPE

Added Payment Info: EVENT_NAME_ADDED_PAYMENT_INFO

SUCCESS

Added to Cart: EVENT_NAME_ADDED_TO_CART

Price of item added

CONTENT_TYPE, CONTENT_ID or CONTENT, and CURRENCY

Added to Wishlist: EVENT_NAME_ADDED_TO_WISHLIST

Price of item added

CONTENT_TYPE, CONTENT_ID or CONTENT, and CURRENCY

Completed Registration: EVENT_NAME_COMPLETED_REGISTRATION

REGISTRATION_METHOD

Completed Tutorial: EVENT_NAME_COMPLETED_TUTORIAL

SUCCESS, and CONTENT_ID or CONTENT

Added Contact Information:
EVENT_NAME_CONTACT

Customized a Product:
EVENT_NAME_CUSTOMIZE_PRODUCT

Donated:
EVENT_NAME_DONATE

Search for a Location:
EVENT_NAME_FIND_LOCATION

Initiated Checkout: EVENT_NAME_INITIATED_CHECKOUT

Total price of items in cart

CONTENT_TYPE, CONTENT_ID or CONTENT,NUM_ITEMS, PAYMENT_INFO_AVAILABLE, and CURRENCY

Purchased: EVENT_NAME_PURCHASED

Price of Purchase

NUM_ITEMS, CONTENT_TYPE, CONTENT_ID or CONTENT, and CURRENCY

Rated:
EVENT_NAME_RATED

Rating given

CONTENT_TYPE , CONTENT_ID or CONTENT, and MAX_RATING_VALUE

Scheduled:
EVENT_NAME_SCHEDULE

Searched: EVENT_NAME_SEARCHED

CONTENT_TYPE, SEARCH_STRING and SUCCESS

Spent Credits: EVENT_NAME_SPENT_CREDITS

Total value of credits spent

CONTENT_TYPE, and CONTENT_ID or CONTENT

Started a Trial:
EVENT_NAME_START_TRIAL

Price of Subscription

ORDER_ID and CURRENCY

Submitted an Application:
EVENT_NAME_SUBMIT_APPLICATION

Subscribed:
EVENT_NAME_SUBSCRIBE

Price of Subscription

ORDER_ID and CURRENCY

Unlocked Achievement: EVENT_NAME_UNLOCKED_ACHIEVEMENT

DESCRIPTION

Viewed Content:
EVENT_NAME_VIEWED_CONTENT

Price of item viewed (if applicable)

CONTENT_TYPE, CONTENT_ID or CONTENT, and CURRENCY

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.

The table below contains parameters typically used with standard events or with your own custom 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.

AppEventConstants::EVENT_PARAM_* Possible Values Description

Ad Type:
EVENT_PARAM_AD_TYPE

string

Type of ad: banner, interstitial, rewarded_video, native

Content ID:

EVENT_PARAM_CONTENT_ID

string

International Article Number (EAN) when applicable, or other product or content identifier

Content:

EVENT_PARAM_CONTENT

string

A list of JSON object that contains the International Article Number (EAN) when applicable, or other product or content identifier(s) as well as additional information about the products. id, quantity, and item_price are the available fields. e.g. "[{\"id\": \"1234\", \"quantity\": 2, \"item_price\": 5.99}, {\"id\": \"5678\", \"quantity\": 1, \"item_price\": 9.99}]"

Content Type:

EVENT_PARAM_CONTENT_TYPE

string

'product' or 'product_group'

Currency:

EVENT_PARAM_CURRENCY

string

ISO 4217 code, e.g., "EUR", "USD", "JPY"

Description:

EVENT_PARAM_DESCRIPTION

string

A string description

Level:

EVENT_PARAM_LEVEL

string

Level of a game

Max. Rating Value:

EVENT_PARAM_MAX_RATING_VALUE

int

Upper bounds of a rating scale, for example 5 on a 5 star scale

Number of Items:

EVENT_PARAM_NUM_ITEMS

int

Number of items

Order ID:

EVENT_PARAM_ORDER_ID

string

The unique ID for all events within a subscription

Payment Info Available:

EVENT_PARAM_PAYMENT_INFO_AVAILABLE

1 or 0

1 for yes, 0 for no

Registration Method:

EVENT_PARAM_REGISTRATION_METHOD

string

Facebook, Email, Twitter, etc.

Search String:

EVENT_PARAM_SEARCH_STRING

string

The text string that was searched for

Success:

EVENT_PARAM_SUCCESS

1 or 0

1 for yes, 0 for no

Custom App Events

You can also create your own custom events that are specific to actions within your app. Use the Code Generator to generate code for these events.

To Generate Code for a Custom Event

  1. Choose the Custom Event tab.
  2. In Event Name, enter the name of your event.
  3. Click Add Event Paramater if you would like to add parameters to your 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 logger is an instance of AppEventsLogger and has been
 * created using AppEventsLogger.newLogger() call.
 */
public void logBattleTheMonsterEvent () {
    logger.logEvent("BattleTheMonster");
}

Take a look at our Example Apps to view some scenarios of using App Events.

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);
    }
}

Limits

The maximum number of different event names is 1000. Once this limit is reached, no new event types will be logged. If you exceed this limit you may see a 100 Invalid parameter error when logging. Read more about event limits in the FAQ.

It is possible to deactivate obsolete events and parameters if you no longer need to track them. If you need to remove an event or parameter, you can deactivate it by following the instructions in our help center.

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 guides should be used as a starting point for your app and should be customized by you.

8. Test Your Events

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 so you can easily verify App Event usage from the client side. The debug logs contain detailed requests and responses in JSON. You can enable debug logs by adding this 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.

More Resources

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