AppsFlyer SDK Integration - Android

android.pngSDK Version:  4.8.7 (Release Notes)

1. Overview

AppsFlyer's SDK provides app installation and event tracking functionality. We have developed an SDK that is highly robust (7+ billion SDK installations to date), secure, lightweight and very simple to embed.

You can track installs, updates and sessions and also track additional in-app events beyond app installs (including in-app purchases, game levels, etc.) to evaluate ROI and user engagement levels.

The AppsFlyer Android SDK is compatible with Android 2.3 and above.

If you're migrating from AppsFlyer's Android SDK V.3.3.x click here.

2. Quick Start

2.1 SDK Download 

To download the Android SDK jar, click here.

For details of AppsFlyer's Sample App, click here.

2.2 Embedding SDK in App

You can integrate the AppsFlyer's SDK either automatically using Gradle's Dependency Management or manually as an SDK.jar.

2.3 Adding the SDK to your Project

The simplest way to integrate the SDK into your project is by using Gradle's Dependency Management. Version info can be found here.

If you are not using Gradle, download and add the AF-Android-SDK.jar to the project's class path.

Adding AppsFlyer's Android SDK Dependency:

  1.  Open your project (or create a new project), and then open your_app | build.gradle
  2.  Add this to Module-level /app/build.gradle before dependencies:
repositories {

Add the compile dependency with the latest version of the AppsFlyer SDK in the 
build.gradle file: 

dependencies {
compile 'com.appsflyer:af-android-sdk:4+@aar'
compile ''


  • The '' dependency is required to support Google's Play Install referrer API. Using this API improves attribution accuracy, protects from install fraud and more.
  • The API is supported from AppsFlyer's Android SDK version 4.8.6 and onwards. If updating from an older SDK version complete this new dependency's integration by updating the SDK's init method.
  • Developers who are using ProGuard and want to use Google's new referrer API must set the following ProGuard rule:

2.4 Setting the Required Permissions

The AndroidManifest.xml should include the following permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Optional : -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

2.5 Setting the BroadcastReceiver in AndroidManifest.xml

The following two options are available for implementing the install referrer broadcast receiver:

Using a Single Broadcast Receiver Using a Multiple Broadcast Receiver

If you do not have a receiver listening on the INSTALL_REFERRER, in the AndroidManifest.xml, add the following receiver within the application tag:

<receiver android:name="com.appsflyer.SingleInstallBroadcastReceiver" android:exported="true">
         <action android:name="" />

3. SDK Initialization

Initialization of the SDK is completed in two stages. In the first stage the DevKey is supplied along with an optional conversionDataListener. In the second stage the call to startTracking indicates that all relevant preparations are complete (e.g. call setCustomerUserId) and the SDK can start tracking all events.

To initialize the SDK, add the following code in your Application onCreate() function:

public class AFApplication extends Application {
   private static final String AF_DEV_KEY = <your-appsflyer-dev-key>;
   public void onCreate() {
       AppsFlyerConversionListener conversionDataListener =
new AppsFlyerConversionListener() {
AppsFlyerLib.getInstance().init(AF_DEV_KEY, getConversionListener(), getApplicationContext());
       AppsFlyerLib.getInstance().startTracking(this);   }


Alternatively, you can delay the call to startTracking and place it within any relevant Activity OnCreate() function.


The following dependancy: compile '' And the getApplicationContext() passed in the following method: AppsFlyerLib.getInstance().init(AF_DEV_KEY, getConversionListener(), getApplicationContext()); are the prerequisite for reporting Google's New Referrer API to AppsFlyer.

Your dev key is accessible from the AppsFlyer Dashboard under the Configuration section inside App Settings:

This API enables AppsFlyer to detect installations, sessions, and updates.

4. Tracking In-App Events

In App Events provide insight on what is happening in your app. It is recommended to take the time and define the events you would like to measure to allow you to track ROI (Return on Investment) and LTV (Lifetime Value).

Tracking in-app events is performed by calling trackEvent with event name and value parameters. See In App Events documentation for more details.


An In-App Event name must be no longer than 45 characters. Events names with more than 45 characters do not appear in the dashboard, but only in the raw Data, Pull and Push APIs.

//context - use getApplicationContext()
//eventName is any string to define the event name.
//eventValues is a map of event parameters that comprise a rich event.  
public static void trackEvent(Context context, String eventName, Map eventValues);

: Level Achieved In-App Event

Map<String, Object> eventValue = new HashMap<String, Object>();

This generates an event of type af_level_achieved with the following event values:
{af_level: 9, af_score: 100}


AppsFlyer supports non-English characters with in-app events, or with any other SDK API, starting from Android SDK version 4.8.1.

5. Tracking Deep Linking


We highly recommend to have Deep Linking integrated in your app. Deep Linking is a crucial part of retargeting campaigns and it is highly recommended to use when running retargeting campaigns.

For each activity that may be used for deep linking (including the main activity if needed) add the following line in the onCreate():


Activities that are meant to be opened by deep linking should have the below intent filter on the activity definitions in the manifest file. 

   <action   android:name="android.intent.action.VIEW" />
   <category android:name="android.intent.category.DEFAULT" />
   <category android:name="android.intent.category.BROWSABLE" />
   <data     android:scheme="yourUniquescheme" />

Scheme configured correlates with the af_dp value you include in your tracking link.

To receive your deep link data, you must implement the callback onAppOpenAttribution called by the AppsFlyer SDK.  It returns the Onelink/tracking link parameters used to trigger the app open. Then, you can parse the values and apply the logic to trigger the relevant app page.

void onAppOpenAttribution(Map<String,String> attributionData);

For more information, click here, or review this article’s Get Conversion Data section.

6. Tracking Revenue

Use the AFEventParamRevenue event parameter to count revenue as part of an in-app event. You can populate it with any numeric value, positive or negative.


AFEventParamRevenue (equivalent to using af_revenue) is the ONLY event parameter that is counted on AppsFlyer as real revenue on the raw data and dashboard. For more details please click here.

Example: Revenue In-App Event

Map<String, Object> eventValue = new HashMap<String, Object>();

This generates an event of type af_purchase with the following event values:

{af_content_id: “1234567”, af_content_type: “category_a”, af_revenue: 200, af_currency: “USD”}

The purchase event above contains a $200 revenue, appearing as revenue in the dashboard. 


Setting user local currency code for in app purchases - the currency code should be a 3 character ISO 4217 code. (default is USD). 

You can set the currency code for all events by calling the following method: AppsFlyer.setCurrencyCode("GBP");

7. Get Conversion Data

AppsFlyer allows you to access the user attribution data in real-time for every new install, directly from the SDK level. By doing this you can serve users with personalized content or send them to specific activities within the app, which can greatly enhance their engagement with your app.

To access AppsFlyer's conversion data from the Android SDK implement the ConversionDataListener:

public interface AppsFlyerConversionListener {
       void onInstallConversionDataLoaded(Map<String,String> conversionData);
       void onInstallConversionFailure(String errorMessage);


AppsFlyerLib.getInstance().registerConversionListener(this, new AppsFlyerConversionListener() {
  public void onInstallConversionDataLoaded(Map<String, String> conversionData) {
      for (String attrName : conversionData.keySet()) {
          Log.d(AppsFlyerLib.LOG_TAG, "attribute: " + attrName + " = " + conversionData.get(attrName));
  public void onInstallConversionFailure(String errorMessage) {
      Log.d(AppsFlyerLib.LOG_TAG, "error getting conversion data: " + errorMessage);
  public void onAppOpenAttribution(Map<String, String> conversionData) {
  public void onAttributionFailure(String errorMessage) {
      Log.d(AppsFlyerLib.LOG_TAG, "error onAttributionFailure : " + errorMessage);

8. User Identifiers

Get AppsFlyer Device ID

AppsFlyer's unique device ID is created for every new install of an app. Use the following API to obtain AppsFlyer’s Unique ID:

public String getAppsFlyerUID(Context context);

Usage Example:

String appsFlyerId = AppsFlyerLib.getInstance().getAppsFlyerUID(this);
Set Customer User ID
Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyer’s unique ID and the other devices’ IDs. This ID is available in AppsFlyer CSV reports along with Postback APIs for cross-referencing with your internal IDs.

To set your Customer User ID:

public void setCustomerUserId(String id);

Usage Example:



The customerUserID SHOULD be set before the trackAppLaunch. It is recommended to set your Customer User ID as soon as possible as it is only associated to events reported after its setup. Customer User ID can also be used to complete integrations with Analytics platforms such as Mixpanel and Swrve.

For more information about the Customer User ID, click here.

Set User Email
AppsFlyer enables you to report one or more of the device’s associated email addresses. You must collect the email addresses and report it to AppsFlyer according to your required encryption method.

The following encryption methods are available: SHA1, MD5, SHA256 and plain.


public void setUserEmails(String... emails);

Usage Example:

AppsFlyerLib.getInstance().setUserEmails(AppsFlyerProperties.EmailsCryptType.MD5, "","", ….);


Personally Identifiable Information (PII) such as email addresses are not retained by AppsFlyer and this information is not presented in any reports. The purpose of collecting this information is solely for postback purposes to the media source.

Google Advertising ID

From SDK Version 4.8.0 AppsFlyer automatically collects the google_advertising_id. The requirement to collect the Google Advertising ID is only relevant for SDK versions 4.7.X and below.

IMEI and Android ID

By default, IMEI and Android ID are not collected by the SDK if the OS version is higher than KitKat (4.4) and the app contains Google Play Services.  

To explicitly send these IDs to AppsFlyer, developers can use the following APIs:


If the app does NOT contain Google Play Services the IMEI and Android ID are collected by the SDK.

Developers can opt-out of collection of IMEI and Android ID by using these APIs:



At least one device identifier, GAID, Android ID or IMEI, MUST be collected to allow for proper attribution.

9. Optional Features

Track Uninstalls
AppsFlyer enables you to track app uninstalls.

To complete this process fully and correctly, you must read here.

Tracking Push Notifications 

AppsFlyer allows you to measure push notifications as part of a retargeting campaign.

To enable this feature, call the next method inside the onCreate method of every Activity which will be launched upon clicking the notification:


The data payload should include an object: af with the relevant key-value string:


\"data\": { \"score\": \"5x1\", \"time\": \"15:10\" , \"af\" : { \"c\" : \"test_campaign\" , \"is_retargeting\" : \"true\" , \"pid\" : \"push_provider_int\" } } }"[with deep-linking] \"data\": { \"score\": \"5x1\", \"time\": \"15:10\", \"click_action\" : \"com.example.someAction\" , 
\"af\" : { \"c\" : \"test_campaign\" , \"is_retargeting\" : \"true\" , \"pid\" : \"push_provider_int\" } } }"


For more information on push notification measurement, read here.

Cross Promotion Tracking 
AppsFlyer allows you to track and attribute installs originating from a cross promotion of one of your apps from within the current app the user has. Cross promoting apps can be a major growth factor in driving additional installs for your apps.

For details, see the Cross Promotion Tracking article, here.
User Invite Tracking
AppsFlyer allows you to track and attribute installs originating from user invites within your app. Allowing your existing users to invite their friends and contacts as new users to your app can be a key growth factor for your app.

For details, see the User Invite Tracking article, here.
Set Currency Code 
You can set a global currency code using the API below, in addition to specific currency codes that can be used as part of each in-app event sent to AppsFlyer. The global currency code is used when af_currency


is not sent as part of an in-app event.

USD is the default value. You can find acceptable ISO currency codes here.

Use the following API to set the currency code:

public void setCurrencyCode(String currencyCode);

Usage Example:

In-App Purchase Validation

AppsFlyer’s SDK provides server verification for in-app purchases. To set purchase validation tracking, call the validateAndTrackInAppPurchase method inside the onActivityResult function.

This call automatically generates an af_purchase in-app event.

public static void validateAndTrackInAppPurchase(
                     Context context,
                     String publicKey,
                     String signature,
                     String purchaseData,
                     String price,
                     String currency,
                     HashMap<String, String> additionalParameters);

This call has two callback blocks, one for ‘Success’ and one for ‘Failure’ (for any reason, including validation fail).

    AppsFlyerInAppPurchaseValidatorListener() {
         public void onValidateInApp() {
             Log.d(TAG, "Purchase validated successfully");
         public void onValidateInAppFailure(String error) {
             Log.d(TAG, "onValidateInAppFailure called: " + error);

Usage Example:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == 1001) {
      String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
      String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
      if (resultCode == RESULT_OK) {
          HashMap<String,String> event = new HashMap<>();
          AppsFlyerLib.getInstance().validateAndTrackInAppPurchase(getApplicationContext(),publicKey, dataSignature, purchaseData, "3.00", "ILS", event);
Anonymize User Data
AppsFlyer provides you with a method to anonymize specific user identifiers in AppsFlyer analytics. This method complies with the latest privacy requirements and complies with Facebook data and privacy policies. Default is NO, meaning no anonymization is performed by default.

Use this API during the SDK Initialization to explicitly anonymize a user's installs, events and sessions:

public void setDeviceTrackingDisabled(boolean isDisabled);

Usage Example:

Tracking can be restarted by calling deviceTrackingDisabled again set to false.


Anonymizing users SEVERELY impacts your attribution information.
Use this option ONLY for regions which legally prevents you from collecting your users' information.
Custom Time Between Sessions
For AppsFlyer to count two separate sessions, the default time between each session must be at least 5 seconds. A session commences when the user opens the app. If you want to configure a different time between sessions, use the following API: AppsFlyerLib.setMinTimeBetweenSessions(int seconds);
Background Sessions for Utility Apps

If your app is a utility app running in the background you can use this API in your activity’s onCreate() -

public void reportTrackSession(Context context);

Usage Example:

Track Out-of-Store Apps 


Google Play is the default store. If you are publishing your app only on Google Play, skip this section.

To track installs out of Google Play, set the channel/store at the app’s AndroidManifest.xml with a unique channel or any store name for each APK. The CHANNEL value is case sensitive.


<meta-data android:name="CHANNEL" android:value="Amazon" />
<meta-data android:name="CHANNEL" android:value="Standalone"/>
<meta-data android:name="CHANNEL" android:value="Verizon" />


You must configure the CHANNEL value at the AppsFlyer dashboard when setting up the app.

Place the meta-data tag before the </application> tag.

For more details on how to track installs for out-of-store apps, read here.

Opt Out

In some extreme cases you might want to shut down all SDK tracking due to legal and privacy compliance. This can be achieved with the isStopTracking API. Once this API is invoked, our SDK will no longer communicate with our servers stop functioning.

AppsFlyerLib.getInstance().stopTracking(true, context);

In any event, the SDK can be reactivated by calling the same API, but to pass false.


Use this API only in cases where you want to fully ignore this user from any and all tracking. Using this API SEVERELY impacts your reporting and attribution..

10. Testing the SDK Integration

To test the SDK integration before and after submitting to the Google Play Store click here.

11. Known Issues

If you are using ProGuard and you encounter a warning regarding our AFKeystoreWrapper class, then add the following code to your ProGuard rules file:

-dontwarn com.appsflyer.AFKeystoreWrapper
Was this article helpful?
8 out of 10 found this helpful



Please sign in to leave a comment.