AppsFlyer SDK Integration - Android v. 4.6-4.7

This Android SDK guide covers all of AppsFlyer's past Android SDK versions 4.6-4.7.

For the latest SDK guide, click here.

For the latest Android SDK release notes, click here.


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 (by following the mandatory steps below), 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 mandatory steps are detailed in sections 2 and 3 below, followed by additional optional features in sections 4 and 5.

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

The following sections are covered in this guide:

 Android SDK Download

To download the Android SDK jar, click here.

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

1.  What’s New in This Version?

  • Bug fixes and maintenance

2.  Embedding the SDK into Your Application (Mandatory)

The following steps are mandatory to measure installs and sessions.

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

2.1  Add the AppsFlyer SDK to your Project

The simplest way to integrate the SDK into your project is by using Gradle's Dependency Management. 

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 {

3.  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'

Version info can be found here

Now you can import AppsFlyer's SDK into your project and integrate it as described in this guide. 

import com.appsflyer.AppsFlyerLib

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

2.2  Set 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" />

* ACCESS_WIFI_STATE and READ_PHONE_STATE permissions are optional.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Adding this permission enables the carrier to track IMEI.

2.3  Set an Install Referrer Broadcast Receiver in AndroidManifest.xml

Android apps cannot have multiple receivers with the same intent-filtered action.

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

2.3.1  Using a Multiple Broadcast Receiver

AppsFlyer provides a solution that broadcasts INSTALL_REFERRER to all other receivers automatically. In the AndroidManifest.xml, add the following receiver as the FIRST receiver for INSTALL_REFERRER, and ensure the receiver tag is within the application tag:

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

If you want to use multiple receivers, the Manifest.xml must appear, as follows:

<!—The AppsFlyer Install Receiver is first and will broadcast to all receivers placed below it -->
<receiver android:name="com.appsflyer.MultipleInstallBroadcastReceiver" android:exported="true">
     <action android:name="" />
<!—All other receivers should follow right after -->     
<receiver android:name="" android:exported="true">
      <action android:name="" />
<receiver android:name="" android:exported="true">
          <action android:name="" />

2.3.2  Using a Single Broadcast Receiver

In the AndroidManifest.xml, add the following receiver as the FIRST receiver for INSTALL_REFERRER or after another multiple broadcast receiver, and ensure the receiver tag is within the application tag:

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

For more information about how to add an additional receiver to access app install data from your app context, click here.

2.4  Embed Google Play Services into Your App

Collecting the Google Advertising ID (GAID) is essential for tracking campaigns across several channels including Facebook, Google and Twitter. 

To add Google Advertising ID:

  1. Install the Google Play Services SDK and import it into your project.  For download details, click here.
  2. Add the following entry to the AndroidManifest.xml as the last entry under application (before </application>):
<meta-data android:name=""
android:value="@integer/google_play_services_version" />


  • AppsFlyer uses the Google Play Services library for retrieving the Google Advertising ID.
  • Google Play Services 7.5 is the minimum requirement for the GCM Registration Token (which is used for our Uninstall measurement).  AppsFlyer recommends to always use the latest version.

Although the library provides additional services, if you use ProGuard as part of your build process, it has a light footprint. We only use the ads packages from Google Services. If you want to optimize the size of your project you can exclude any other packages.

For more details see


2.5  Collecting Android ID and IMEI

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:


NOTE: At least one device identifier should be collected to allow for proper attribution.

3.  SDK Initialization and Installation Event (Minimum Requirement for Tracking)

NOTE: This is the minimum requirement to begin tracking your app installs.

3.1  Initializing the SDK

To initialize the SDK, add the following code to your onCreate function:

public void startTracking(Application application, String key);

Usage Example:


Replace [Dev_Key] with your own Dev_Key (accessible from your account, see Settings >> Integrate the SDK into... in the AppsFlyer dashboard).

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

3.2  Reporting Deep Links for Retargeting Attribution

If your app supports deep linking or has multiple activities or you plan to run retargeting campaigns, you must implement the steps in section 5.6

3.3  Reporting Background Sessions

If your app is a utility app running in the background you can use the API as described in section 5.12 to measure sessions and retention within AppsFlyer.

4.  In-App Events Tracking API (Optional)

This API enables AppsFlyer to track post install events. These events are defined by the advertiser and include an event name, in addition to optional event values.

Tracking in-app events helps you measure and analyze how loyal users discover your app, and attribute them to specific campaigns/media sources. It is recommended to take the time and define the events you want to measure to allow you to track ROI (Return on Investment) and LTV (Lifetime Value).


public static void trackEvent(Context context, String eventName, Map eventValues)

context - use getApplicationContext()

eventName is any string to define the event name.

eventValues is a map of event parameters that comprise a rich event.  

Counting revenue as part of a rich in-app event: Use the af_revenue (constant)


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

NOTE:  af_price 


is not counted as revenue and is a descriptive parameter which does not affect revenue and LTV measurements.

Example 1: 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}

Example 2: Purchase 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.

NOTE: 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.

For details of the AppsFlyer Rich In-App Events for Android, click here.

5.  Advanced Integration

The APIs below are optional and are part of the advanced integration with the AppsFlyer SDK.

5.1  Set Currency Code (Optional)

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:


5.2  Get AppsFlyer Unique ID (Optional)

An AppsFlyer proprietary unique ID is created for every new install of an app. AppsFlyer’s unique ID is the main ID used by AppsFlyer in the Reports and APIs.

Use the following API to obtain AppsFlyer’s unique ID:

public String getAppsFlyerUID(Context context);

Usage Example:

String appsFlyerId = AppsFlyerLib.getInstance().getAppsFlyerUID(this);

5.3  Set Customer User ID (Optional)

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:



  • It is recommended to set your Customer User ID as soon as possible as it is only associated to events reported after setting this attribute.
  • You must set the Customer User ID using this API to use AppsFlyer’s integrations with Analytics platforms such as Mixpanel and Swrve.

5.4  Get Conversion Data (Optional)

AppsFlyer allows you to access the user attribution data in real-time directly at SDK level. It enables you to customize the landing page a user sees on the very first app open after a fresh app install.

For more information regarding this advanced functionality, read here.

5.5  Set User Email (Optional)

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 and plain.


public void setUserEmails(String... emails);

Usage Example:

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

NOTE : 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.

5.6  Reporting Deep Links for Retargeting Attribution (Optional)

Deep Linking is a crucial part of retargeting campaigns and it is highly recommended to use when running retargeting campaigns.

For each activity used for deep linking*, other than the main activity, 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="your unique scheme" />

5.7  In-App Purchase Validation (Optional)

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

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

Usage Example:

AppsFlyerLib.getInstance().validateAndTrackInAppPurchase(context,publicKey, signature, purchaseData, price,currency, null;

5.8  End User Opt-Out (Optional)

AppsFlyer provides you a method to opt‐out specific users from AppsFlyer analytics. This method complies with the latest privacy requirements and complies with Facebook data and privacy policies. Default is NO, meaning tracking is enabled by default.

Use this API during the SDK initialization in Section 4 to explicitly opt-out:

public void setDeviceTrackingDisabled(boolean isDisabled);

Usage Example:


5.9  Track App Installs Out of Google Play (Optional)

IMPORTANT NOTE: 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 appAndroidManifest.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"/>

Verizon (Pre-Installed):

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

NOTE: 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.

5.10 Track App Uninstalls

AppsFlyer enables you to track app uninstalls.

Add the following permissions to the manifest.  (Apps using push notifications should already have these permissions)

<uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission android:name="YOUR-PACKAGE-NAME.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="<your-package-name>.permission.C2D_MESSAGE" /> <uses-permission android:name="" />
NOTE: Enter the correct name of your package.
Add the following receiver before the </application> tag:
<action android:name="" />
<service android:name="com.appsflyer.InstanceIDListener" android:exported="false">
<action android:name=""/>
Set the GCM Project Number on your main activity: Add this line immediately before the call to the startTracking():
public void setGCMProjectNumber(Context context, String id);
Usage Example:
AppsFlyerLib.getInstance().setGCMProjectNumber(this, '1234567890');
To complete this process fully and correctly, you must read here.

5.11 Implementing Deep Linking with OneLink (Optional)

OneLink triggers an app to open at the deep Link location by mentioning the scheme under the af_dp parameter.

You must implement the callback onAppOpenAttribution called by the AppsFlyer SDK.  It returns the Onelink 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); //android
For more information, click here.

5.12 Report Background Session (Optional)

This is a recommended API for utility apps that want to measure user retention while running in the background.
public void reportTrackSession(Context context);
Usage Example:

5.13  Push Notification Measurements (Optional)

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:
\"af\" : { \"c\" : \"test_campaign\" , \"is_retargeting\" : \"true\" , \"pid\" : \"push_provider_int\" })
Usage Example:
\"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\" } } }"


6.  Testing the SDK Integration

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

7.  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?
0 out of 0 found this helpful



Please sign in to leave a comment.