AppsFlyer SDK Integration - Android

Current Version:  4.8.4

 Note

There was a major version change to a previous version of the SDK.  For details of the migration from V.3.3.x to 4.6.6 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 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.

1. Android SDK Download

To download the Android SDK jar, click here.

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

2. Embedding the SDK into Your Application

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

2.1 Adding the AppsFlyer 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 {
mavenCentral()
}


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'
}

2.2 Setting the Required Permissions

The AndroidManifest.xml should include the following permission:

<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.3 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">
    <intent-filter>
         <action android:name="com.android.vending.INSTALL_REFERRER" />
     </intent-filter>
</receiver>

3. Configuring the SDK

Follow the steps below to configure the SDK.

3.1 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 will indicate that all relevant perparations were completed (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>;
   @Override
   public void onCreate() {
       super.onCreate();
       AppsFlyerConversionListener conversionDataListener =
new AppsFlyerConversionListener() {
           ...
       };
       AppsFlyerLib.getInstance().init(AF_DEV_KEY, conversionDataListener);
       AppsFlyerLib.getInstance().startTracking(this);   }
}

 Note

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

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 DeepLinking

 Tip

We highly recommend to have DeepLinking integrated in your app. DeepLinking is a crucial part of re-targeting campaigns and it is highly recommended to use when running re-targeting campaigns.

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

AppsFlyerLib.getInstance().sendDeepLinkData(this);

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

<intent-filter>
   <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" />
</intent-filter>


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

To receive your deeplink 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.

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

 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.

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


Example
: Level Achieved In-App Event

Map<String, Object> eventValue = new HashMap<String, Object>();
eventValue.put(AFInAppEventParameterName.LEVEL,9);
eventValue.put(AFInAppEventParameterName.SCORE,100);
AppsFlyerLib.getInstance().trackEvent(context,AFInAppEventType.LEVEL_ACHIEVED,eventValue);
This generates an event of type af_level_achieved with the following event values:
{af_level: 9, af_score: 100}

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.

 Note

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>();
eventValue.put(AFInAppEventParameterName.REVENUE,200);
eventValue.put(AFInAppEventParameterName.CONTENT_TYPE,"category_a");
eventValue.put(AFInAppEventParameterName.CONTENT_ID,"1234567");
eventValue.put(AFInAppEventParameterName.CURRENCY,"USD");
AppsFlyerLib.getInstance().trackEvent(context,AFInAppEventType.PURCHASE,eventValue);

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. 

7. Attribution Data

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.

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


Example:

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

8. User Identifiers

Get AppsFlyer Unique ID (Optional)

An AppsFlyer proprietary unique 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:

AppsFlyerLib.getInstance().setCustomerUserId("myId");

 Note

You must set your Customer User ID before calling startTracking 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.

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

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

Example:

public void setUserEmails(String... emails);


Usage Example:

AppsFlyerLib.getInstance().setUserEmails(AppsFlyerProperties.EmailsCryptType.MD5, "email1@domain.com","email2@domain.com", ….);

 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.

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.

9. Optional Features

End User Opt-Out 
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 to explicitly opt-out:

public void setDeviceTrackingDisabled(boolean isDisabled);


Usage Example:

AppsFlyerLib.getInstance().setDeviceTrackingDisabled(true);
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:

AppsFlyerLib.getInstance().reportTrackSession(context);
java
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).

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:

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<>();
          event.put(AFInAppEventParameterName.PRICE,"9");
          AppsFlyerLib.getInstance().validateAndTrackInAppPurchase(getApplicationContext(),publicKey, dataSignature, purchaseData, "3.00", "ILS", event);
      }
  }
} 
Track Uninstalls
AppsFlyer enables you to track app uninstalls.

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

Push Notification Measurements 

AppsFlyer allows you to measure push notifications as part of a re-targeting campaign.

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

AppsFlyerLib.getInstance().sendPushNotificationData(this);

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

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\" } } }"

 Note

For more information on push notification measurement, read here.

Track Out-of-Store Apps 

 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 app’s AndroidManifest.xml with a unique channel or any store name for each APK. The CHANNEL value is case sensitive.

Examples:

<meta-data android:name="CHANNEL" android:value="Amazon" />
<meta-data android:name="CHANNEL" android:value="Standalone"/>
<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.

Collecting Device Identifiers 

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:

AppsFlyerLib.getInstance().setImeiData("IMEI_DATA_HERE")
AppsFlyerLib.getInstance().setAndroidIdData("ANDROID_ID_DATA_HERE")

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:

AppsFlyerLib.getInstance().setCollectIMEI(false)
AppsFlyerLib.getInstance().setCollectAndroidID(false)

 Note

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

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

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

AppsFlyerLib.getInstance().setCurrencyCode("GBP");
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.
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)

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