Android SDK Version
  • java.lang.Object
    • com.facebook.appevents.AppEventsLogger

public class AppEventsLogger
extends java.lang.Object
The AppEventsLogger class allows the developer to log various types of events back to Facebook. In order to log events, the app must create an instance of this class via a newLogger method, and then call the various "log" methods off of that.
This client-side event logging is then available through Facebook App Insights and for use with Facebook Ads conversion tracking and optimization.
The AppEventsLogger class has a few related roles:
  • Logging predefined and application-defined events to Facebook App Insights with a numeric value to sum across a large number of events, and an optional set of key/value parameters that define "segments" for this event (e.g., 'purchaserStatus' : 'frequent', or 'gamerLevel' : 'intermediate'). These events may also be used for ads conversion tracking, optimization, and other ads related targeting in the future.
  • Methods that control the way in which events are flushed out to the Facebook servers.
Here are some important characteristics of the logging mechanism provided by AppEventsLogger:
  • Events are not sent immediately when logged. They're cached and flushed out to the Facebook servers in a number of situations:
    • when an event count threshold is passed (currently 100 logged events).
    • when a time threshold is passed (currently 15 seconds).
    • when an app has gone to background and is then brought back to the foreground.
  • Events will be accumulated when the app is in a disconnected state, and sent when the connection is restored and one of the above 'flush' conditions are met.
  • The AppEventsLogger class is intended to be used from the thread it was created on. Multiple AppEventsLoggers may be created on other threads if desired.
  • The developer can call the setFlushBehavior method to force the flushing of events to only occur on an explicit call to the `flush` method.
  • The developer can turn on console debug output for event logging and flushing to the server by calling FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS);
Some things to note when logging events:
  • There is a limit on the number of unique event names an app can use, on the order of 1000.
  • There is a limit to the number of unique parameter names in the provided parameters that can be used per event, on the order of 25. This is not just for an individual call, but for all invocations for that eventName.
  • Event names and parameter names must be between 2 and 40 characters, and must consist of alphanumeric characters, _, -, or spaces.
  • The length of each parameter value can be no more than on the order of 100 characters.
Nested Class Summary
Modifier and TypeClass and Description
static class AppEventsLogger.FlushBehavior
Controls when an AppEventsLogger sends log events to the server
static class AppEventsLogger.ProductAvailability
Product availability for Product Catalog product item update
static class AppEventsLogger.ProductCondition
Product condition for Product Catalog product item update
Field Summary
Modifier and TypeField and Description
static java.lang.StringACTION_APP_EVENTS_FLUSHED
The action used to indicate that a flush of app events has occurred.
static java.lang.StringAPP_EVENTS_EXTRA_FLUSH_RESULT 
static java.lang.StringAPP_EVENTS_EXTRA_NUM_EVENTS_FLUSHED 
Method Summary
Modifier and TypeMethod and Description
static voidactivateApp(Application application)
Notifies the events system that the app has launched and activate and deactivate events should start being logged automatically.
static voidactivateApp(Application application, java.lang.String applicationId)
Notifies the events system that the app has launched and activate and deactivate events should start being logged automatically.
static voidactivateApp(Context _context)
Deprecated. 
static voidactivateApp(Context context, java.lang.String _str)
Deprecated. 
static voidaugmentWebView(WebView webView, Context context)
Intended to be used as part of a hybrid webapp.
static voidclearUserData()
Clears the current user data
static voidclearUserID()
Clears the currently set user id.
static voiddeactivateApp(Context _context)
Deprecated. 
When using activateApp(Application) deactivate app will be logged automatically.
static voiddeactivateApp(Context _context, java.lang.String _str)
Deprecated. 
When using activateApp(Application) deactivate app will be logged automatically.
voidflush()
Explicitly flush any stored events to the server.
static java.lang.StringgetAnonymousAppDeviceGUID(Context context)
Each app/device pair gets an GUID that is sent back with App Events and persisted with this app/device pair.
java.lang.StringgetApplicationId()
Returns the app ID this logger was configured to log to.
static AppEventsLogger.FlushBehaviorgetFlushBehavior()
Access the behavior that AppEventsLogger uses to determine when to flush logged events to the server.
static java.lang.StringgetUserData()
Returns the set user data else null.
static java.lang.StringgetUserID()
Returns the set user id else null.
static voidinitializeLib(Context context, java.lang.String applicationId)
Notifies the events system which internal SDK Libraries, and some specific external Libraries that the app is utilizing.
booleanisValidForAccessToken(AccessToken accessToken)
Determines if the logger is valid for the given access token.
voidlogEvent(java.lang.String eventName)
Log an app event with the specified name.
voidlogEvent(java.lang.String eventName, Bundle parameters)
Log an app event with the specified name and set of parameters.
voidlogEvent(java.lang.String eventName, double valueToSum)
Log an app event with the specified name and the supplied value.
voidlogEvent(java.lang.String eventName, double valueToSum, Bundle parameters)
Log an app event with the specified name, supplied value, and set of parameters.
voidlogProductItem(java.lang.String itemID, AppEventsLogger.ProductAvailability availability, AppEventsLogger.ProductCondition condition, java.lang.String description, java.lang.String imageLink, java.lang.String link, java.lang.String title, java.math.BigDecimal priceAmount, java.util.Currency currency, java.lang.String gtin, java.lang.String mpn, java.lang.String brand, Bundle parameters)
Uploads product catalog product item as an app event.
voidlogPurchase(java.math.BigDecimal purchaseAmount, java.util.Currency currency)
Logs a purchase event with Facebook, in the specified amount and with the specified currency.
voidlogPurchase(java.math.BigDecimal purchaseAmount, java.util.Currency currency, Bundle parameters)
Logs a purchase event with Facebook explicitly, in the specified amount and with the specified currency.
voidlogPurchaseImplicitly(java.math.BigDecimal purchaseAmount, java.util.Currency currency, Bundle parameters)
Deprecated. 
Use AppEventsLogger#logPurchase( java.math.BigDecimal, java.util.Currency, android.os.Bundle) instead.
voidlogPushNotificationOpen(Bundle payload)
Logs an app event that tracks that the application was open via Push Notification.
voidlogPushNotificationOpen(Bundle payload, java.lang.String action)
Logs an app event that tracks that the application was open via Push Notification.
voidlogSdkEvent(java.lang.String eventName, java.lang.Double valueToSum, Bundle parameters)
Deprecated. 
static AppEventsLoggernewLogger(Context context)
Build an AppEventsLogger instance to log events through.
static AppEventsLoggernewLogger(Context context, AccessToken accessToken)
Build an AppEventsLogger instance to log events through.
static AppEventsLoggernewLogger(Context context, java.lang.String applicationId)
Build an AppEventsLogger instance to log events that are attributed to the application but not to any particular Session.
static AppEventsLoggernewLogger(Context context, java.lang.String applicationId, AccessToken accessToken)
Build an AppEventsLogger instance to log events through.
static voidonContextStop()
Call this when the consuming Activity/Fragment receives an onStop() callback in order to persist any outstanding events to disk so they may be flushed at a later time.
static voidsetFlushBehavior(AppEventsLogger.FlushBehavior flushBehavior)
Set the behavior that this AppEventsLogger uses to determine when to flush logged events to the server.
static voidsetInstallReferrer(java.lang.String referrer) 
static voidsetPushNotificationsRegistrationId(java.lang.String registrationId)
Sets and sends registration id to register the current app for push notifications.
static voidsetUserData(Bundle userData)
Deprecated. 
static voidsetUserData(java.lang.String email, java.lang.String firstName, java.lang.String lastName, java.lang.String phone, java.lang.String dateOfBirth, java.lang.String gender, java.lang.String city, java.lang.String state, java.lang.String zip, java.lang.String country)
Sets user data to associate with all app events.
static voidsetUserID(java.lang.String userID)
Sets a user id to associate with all app events.
static voidupdateUserProperties(Bundle parameters, GraphRequest.Callback callback) 
static voidupdateUserProperties(Bundle parameters, java.lang.String applicationID, GraphRequest.Callback callback) 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Field Detail

ACTION_APP_EVENTS_FLUSHED

public static final java.lang.String ACTION_APP_EVENTS_FLUSHED
The action used to indicate that a flush of app events has occurred. This should be used as an action in an IntentFilter and BroadcastReceiver registered with the android.support.v4.content.LocalBroadcastManager.

APP_EVENTS_EXTRA_NUM_EVENTS_FLUSHED

public static final java.lang.String APP_EVENTS_EXTRA_NUM_EVENTS_FLUSHED

APP_EVENTS_EXTRA_FLUSH_RESULT

public static final java.lang.String APP_EVENTS_EXTRA_FLUSH_RESULT
Method Detail

activateApp

public static void activateApp(Application application)
Notifies the events system that the app has launched and activate and deactivate events should start being logged automatically. By default this function is called automatically from sdkInitialize() flow. In case 'com.facebook.sdk.AutoLogAppEventsEnabled' manifest setting is set to false, it should typically be called from the OnCreate method of you application.
Parameters:
application - The running application

activateApp

public static void activateApp(Application application,
                               java.lang.String applicationId)
Notifies the events system that the app has launched and activate and deactivate events should start being logged automatically. By default this function is called automatically from sdkInitialize() flow. In case 'com.facebook.sdk.AutoLogAppEventsEnabled' manifest setting is set to false, it should typically be called from the OnCreate method of you application. Call this if you wish to use a different Application ID then the one specified in the Facebook SDK.
Parameters:
application - The running application
applicationId - The application id used to log activate/deactivate events.

activateApp

@Deprecated
public static void activateApp(Context _context)
Deprecated. Use activateApp(Application)

activateApp

@Deprecated
public static void activateApp(Context context,
                                           java.lang.String _str)
Deprecated. Use activateApp(Application)

deactivateApp

@Deprecated
public static void deactivateApp(Context _context)
Deprecated. When using activateApp(Application) deactivate app will be logged automatically.

deactivateApp

@Deprecated
public static void deactivateApp(Context _context,
                                             java.lang.String _str)
Deprecated. When using activateApp(Application) deactivate app will be logged automatically.

initializeLib

public static void initializeLib(Context context,
                                 java.lang.String applicationId)
Notifies the events system which internal SDK Libraries, and some specific external Libraries that the app is utilizing. This is called internally and does NOT need to be called externally.
Parameters:
context - The Context
applicationId - The String applicationId

newLogger

public static AppEventsLogger newLogger(Context context)
Build an AppEventsLogger instance to log events through. The Facebook app that these events are targeted at comes from this application's metadata. The application ID used to log events will be determined from the app ID specified in the package metadata.
Parameters:
context - Used to access the applicationId and the attributionId for non-authenticated users.
Returns:
AppEventsLogger instance to invoke log* methods on.

newLogger

public static AppEventsLogger newLogger(Context context,
                                        AccessToken accessToken)
Build an AppEventsLogger instance to log events through.
Parameters:
context - Used to access the attributionId for non-authenticated users.
accessToken - Access token to use for logging events. If null, the active access token will be used, if any; if not the logging will happen against the default app ID specified in the package metadata.

newLogger

public static AppEventsLogger newLogger(Context context,
                                        java.lang.String applicationId,
                                        AccessToken accessToken)
Build an AppEventsLogger instance to log events through.
Parameters:
context - Used to access the attributionId for non-authenticated users.
applicationId - Explicitly specified Facebook applicationId to log events against. If null, the default app ID specified in the package metadata will be used.
accessToken - Access token to use for logging events. If null, the active access token will be used, if any; if not the logging will happen against the default app ID specified in the package metadata.
Returns:
AppEventsLogger instance to invoke log* methods on.

newLogger

public static AppEventsLogger newLogger(Context context,
                                        java.lang.String applicationId)
Build an AppEventsLogger instance to log events that are attributed to the application but not to any particular Session.
Parameters:
context - Used to access the attributionId for non-authenticated users.
applicationId - Explicitly specified Facebook applicationId to log events against. If null, the default app ID specified in the package metadata will be used.
Returns:
AppEventsLogger instance to invoke log* methods on.

getFlushBehavior

public static AppEventsLogger.FlushBehavior getFlushBehavior()
Access the behavior that AppEventsLogger uses to determine when to flush logged events to the server. This setting applies to all instances of AppEventsLogger.
Returns:
Specified flush behavior.

setFlushBehavior

public static void setFlushBehavior(AppEventsLogger.FlushBehavior flushBehavior)
Set the behavior that this AppEventsLogger uses to determine when to flush logged events to the server. This setting applies to all instances of AppEventsLogger.
Parameters:
flushBehavior - the desired behavior.

logEvent

public void logEvent(java.lang.String eventName)
Log an app event with the specified name.
Parameters:
eventName - eventName used to denote the event. Choose amongst the EVENT_NAME_* constants in AppEventsConstants when possible. Or create your own if none of the EVENT_NAME_* constants are applicable. Event names should be 40 characters or less, alphanumeric, and can include spaces, underscores or hyphens, but must not have a space or hyphen as the first character. Any given app should have no more than 1000 distinct event names.

logEvent

public void logEvent(java.lang.String eventName,
                     double valueToSum)
Log an app event with the specified name and the supplied value.
Parameters:
eventName - eventName used to denote the event. Choose amongst the EVENT_NAME_* constants in AppEventsConstants when possible. Or create your own if none of the EVENT_NAME_* constants are applicable. Event names should be 40 characters or less, alphanumeric, and can include spaces, underscores or hyphens, but must not have a space or hyphen as the first character. Any given app should have no more than 1000 distinct event names. * @param eventName
valueToSum - a value to associate with the event which will be summed up in Insights for across all instances of the event, so that average values can be determined, etc.

logEvent

public void logEvent(java.lang.String eventName,
                     Bundle parameters)
Log an app event with the specified name and set of parameters.
Parameters:
eventName - eventName used to denote the event. Choose amongst the EVENT_NAME_* constants in AppEventsConstants when possible. Or create your own if none of the EVENT_NAME_* constants are applicable. Event names should be 40 characters or less, alphanumeric, and can include spaces, underscores or hyphens, but must not have a space or hyphen as the first character. Any given app should have no more than 1000 distinct event names.
parameters - A Bundle of parameters to log with the event. Insights will allow looking at the logs of these events via different parameter values. You can log on the order of 25 parameters with each distinct eventName. It's advisable to limit the number of unique values provided for each parameter in the thousands. As an example, don't attempt to provide a unique parameter value for each unique user in your app. You won't get meaningful aggregate reporting on so many parameter values. The values in the bundles should be Strings or numeric values.

logEvent

public void logEvent(java.lang.String eventName,
                     double valueToSum,
                     Bundle parameters)
Log an app event with the specified name, supplied value, and set of parameters.
Parameters:
eventName - eventName used to denote the event. Choose amongst the EVENT_NAME_* constants in AppEventsConstants when possible. Or create your own if none of the EVENT_NAME_* constants are applicable. Event names should be 40 characters or less, alphanumeric, and can include spaces, underscores or hyphens, but must not have a space or hyphen as the first character. Any given app should have no more than 1000 distinct event names.
valueToSum - a value to associate with the event which will be summed up in Insights for across all instances of the event, so that average values can be determined, etc.
parameters - A Bundle of parameters to log with the event. Insights will allow looking at the logs of these events via different parameter values. You can log on the order of 25 parameters with each distinct eventName. It's advisable to limit the number of unique values provided for each parameter in the thousands. As an example, don't attempt to provide a unique parameter value for each unique user in your app. You won't get meaningful aggregate reporting on so many parameter values. The values in the bundles should be Strings or numeric values.

logPurchase

public void logPurchase(java.math.BigDecimal purchaseAmount,
                        java.util.Currency currency)
Logs a purchase event with Facebook, in the specified amount and with the specified currency.
Parameters:
purchaseAmount - Amount of purchase, in the currency specified by the 'currency' parameter. This value will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
currency - Currency used to specify the amount.

logPurchase

public void logPurchase(java.math.BigDecimal purchaseAmount,
                        java.util.Currency currency,
                        Bundle parameters)
Logs a purchase event with Facebook explicitly, in the specified amount and with the specified currency. Additional detail about the purchase can be passed in through the parameters bundle.
Parameters:
purchaseAmount - Amount of purchase, in the currency specified by the 'currency' parameter. This value will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
currency - Currency used to specify the amount.
parameters - Arbitrary additional information for describing this event. This should have no more than 24 entries, and keys should be mostly consistent from one purchase event to the next.

logPurchaseImplicitly

@Deprecated
public void logPurchaseImplicitly(java.math.BigDecimal purchaseAmount,
                                              java.util.Currency currency,
                                              Bundle parameters)
Deprecated. Use AppEventsLogger#logPurchase( java.math.BigDecimal, java.util.Currency, android.os.Bundle) instead.

logPushNotificationOpen

public void logPushNotificationOpen(Bundle payload)
Logs an app event that tracks that the application was open via Push Notification.
Parameters:
payload - Notification payload received.

logPushNotificationOpen

public void logPushNotificationOpen(Bundle payload,
                                    java.lang.String action)
Logs an app event that tracks that the application was open via Push Notification.
Parameters:
payload - Notification payload received.

logProductItem

public void logProductItem(java.lang.String itemID,
                           AppEventsLogger.ProductAvailability availability,
                           AppEventsLogger.ProductCondition condition,
                           java.lang.String description,
                           java.lang.String imageLink,
                           java.lang.String link,
                           java.lang.String title,
                           java.math.BigDecimal priceAmount,
                           java.util.Currency currency,
                           java.lang.String gtin,
                           java.lang.String mpn,
                           java.lang.String brand,
                           Bundle parameters)
Uploads product catalog product item as an app event.
Parameters:
itemID - Unique ID for the item. Can be a variant for a product. Max size is 100.
availability - If item is in stock. Accepted values are: in stock - Item ships immediately out of stock - No plan to restock preorder - Available in future available for order - Ships in 1-2 weeks discontinued - Discontinued
condition - Product condition: new, refurbished or used.
description - Short text describing product. Max size is 5000.
imageLink - Link to item image used in ad.
link - Link to merchant's site where someone can buy the item.
title - Title of item.
priceAmount - Amount of purchase, in the currency specified by the 'currency' parameter. This value will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
currency - Currency used to specify the amount.
gtin - Global Trade Item Number including UPC, EAN, JAN and ISBN
mpn - Unique manufacture ID for product
brand - Name of the brand Note: Either gtin, mpn or brand is required.
parameters - Optional fields for deep link specification.

flush

public void flush()
Explicitly flush any stored events to the server. Implicit flushes may happen depending on the value of getFlushBehavior. This method allows for explicit, app invoked flushing.

onContextStop

public static void onContextStop()
Call this when the consuming Activity/Fragment receives an onStop() callback in order to persist any outstanding events to disk so they may be flushed at a later time. The next flush (explicit or not) will check for any outstanding events and if present, include them in that flush. Note that this call may trigger an I/O operation on the calling thread. Explicit use of this method is necessary.

isValidForAccessToken

public boolean isValidForAccessToken(AccessToken accessToken)
Determines if the logger is valid for the given access token.
Parameters:
accessToken - The access token to check.
Returns:
True if the access token is valid for this logger.

setPushNotificationsRegistrationId

public static void setPushNotificationsRegistrationId(java.lang.String registrationId)
Sets and sends registration id to register the current app for push notifications.
Parameters:
registrationId - RegistrationId received from FCM.

augmentWebView

public static void augmentWebView(WebView webView,
                                  Context context)
Intended to be used as part of a hybrid webapp. If you call this method, the FB SDK will add a new JavaScript interface into your webview. If the FB Pixel is used within the webview, and references the app ID of this app, then it will detect the presence of this injected JavaScript object and pass Pixel events back to the FB SDK for logging using the AppEvents framework.
Parameters:
webView - The webview to augment with the additional JavaScript behaviour
context - Used to access the applicationId and the attributionId for non-authenticated users.

setUserID

public static void setUserID(java.lang.String userID)
Sets a user id to associate with all app events. This can be used to associate your own user id with the app events logged from this instance of an application. The user ID will be persisted between application instances.
Parameters:
userID - A User ID

getUserID

public static java.lang.String getUserID()
Returns the set user id else null.

clearUserID

public static void clearUserID()
Clears the currently set user id.

setUserData

@Deprecated
public static void setUserData(Bundle userData)
Deprecated. 
Sets user data to associate with all app events. All user data are hashed and used to match Facebook user from this instance of an application. The user data will be persisted between application instances.
Parameters:
userData - user data to identify the user. User data should be formated as a bundle of data type name and value. Supported data types and names are: Email: em First Name: fn Last Name: ln Phone: ph Date of Birth: db Gender: ge City: ct State: st Zip: zp Country: country

setUserData

public static void setUserData(java.lang.String email,
                               java.lang.String firstName,
                               java.lang.String lastName,
                               java.lang.String phone,
                               java.lang.String dateOfBirth,
                               java.lang.String gender,
                               java.lang.String city,
                               java.lang.String state,
                               java.lang.String zip,
                               java.lang.String country)
Sets user data to associate with all app events. All user data are hashed and used to match Facebook user from this instance of an application. The user data will be persisted between application instances.
Parameters:
email - user's email
firstName - user's first name
lastName - user's last name
phone - user's phone
dateOfBirth - user's date of birth
gender - user's gender
city - user's city
state - user's state
zip - user's zip
country - user's country

getUserData

public static java.lang.String getUserData()
Returns the set user data else null.

clearUserData

public static void clearUserData()
Clears the current user data

updateUserProperties

public static void updateUserProperties(Bundle parameters,
                                        GraphRequest.Callback callback)

updateUserProperties

public static void updateUserProperties(Bundle parameters,
                                        java.lang.String applicationID,
                                        GraphRequest.Callback callback)

logSdkEvent

@Deprecated
public void logSdkEvent(java.lang.String eventName,
                                    java.lang.Double valueToSum,
                                    Bundle parameters)
Deprecated. 
This method is only for internal and use by the Facebook SDK account kit for legacy reason. Other usage is not allowed.

getApplicationId

public java.lang.String getApplicationId()
Returns the app ID this logger was configured to log to.
Returns:
the Facebook app ID

getAnonymousAppDeviceGUID

public static java.lang.String getAnonymousAppDeviceGUID(Context context)
Each app/device pair gets an GUID that is sent back with App Events and persisted with this app/device pair.
Parameters:
context - The application context.
Returns:
The GUID for this app/device pair.

setInstallReferrer

public static void setInstallReferrer(java.lang.String referrer)