Integrating the Android SDK

Last Updated: Jun 29, 2017 01:12PM PDT

1. Initial Requirements and Information

Before installing the SDK into your application, please review the following items to ensure integrating the SDK into your application is a smooth and easy process:

  • Apsalar’s latest Android SDKs, 6.X.X, supports Android 4.0.1 (Ice Cream Sandwich) and higher; please be sure you’re using a compatible version of Android’s framework for your application.
    • Apsalar’s SDK reports using the Android Advertising ID for devices using PlayStore v4. Older devices will continue to report using the ANDI.
    • Please note, use of the latest 6.X.X SDK has not been tested with Android versions lower than 4.0.1. Should you choose to use the latest 6.X.X SDK with an Android version lower than 4.0.1, Apsalar’s Product Support Team may not be able to assist with any issues that arise.

2. Download the SDK

Log in and download the SDK by selecting Get the SDK under Developer Tools.

3. Import Apsalar and Required Libraries

  • Unzip the SDK package and add the Apsalar.jar into the libs folder of your Android application project’s libs directory. If not present then create one directory named libs in your project folder. (Generally like /app/libs)
  • Include Google Play Services API 7.5 or higher. If you haven’t added this API to your application already, follow the Setup Guide provided by Google to implement support for Google Play Services API in your application.
    • Minimal requirement can be fulfilled by adding below dependency in application’s build.gradle file -
    • compile ‘’

To use Proguard with your app

  • Add the following lines of code to your proguard.config file:

    -keep class com.apsalar.sdk.** { *; }

4. Add Necessary Permissions to your Application’s Manifest File

The following list of permissions are those which Apsalar’s SDK can utilize; each desired permission should be added in the <manifest> tag in your AndroidManifest.xml file. Please refer to the list below to understand which permissions are required and which are optional:

  • INTERNET - Required

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


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

Please note, Android SDKs 4.X.X and 6.0.X required the WRITE_EXTERNAL_STORAGE permission, which is no longer required for SDKs 6.1.X+.

5. Add Install Referrer Receiver

In most cases, your app will have other broadcast receivers. In these cases, be sure to pass the install referrer to the Apsalar receiver as below. The below example uses an existing INSTALL_REFERRER BroadcastReceiver named MyCustomInstallReciever.

public class MyCustomInstallReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        //First, pass on detail to ApsalarInstallReceiver
        new ApsalarInstallReceiver().onReceive(context, intent);

Alternative Implementation

Alternatively, you can choose to allow the Apsalar SDK to register the receiver by simply adding the following to your tag in your manifest file. Note: this is less common and should only be used if the Apsalar SDK is to be the only INSTALL_REFERRER receiver implementation

<receiver android:exported="true" android:name="com.Apsalar.sdk.ApsalarInstallReceiver">
           <action android:name="" />

Instructions for testing the implementation of the Apsalar Receiver can be found in our SDK Console Guide.

6. Initializing Apsalar SDK

Import the Apsalar Library

Start off by importing the Apsalar library

import com.apsalar.sdk.*;

Build the ApsalarConfig

The ApsalarConfig is the initializing point for enabling sessions, events, and other platform features to be used. To initialize the ApsalarConfig and SDK, you must have Apsalar API key and secret. Your API Key and secret can be obtained from the Get the SDK page in your dashboard. The ApsalarConfig should

The ApsalarConfig is defined like below:

public ApsalarConfig(String apiKey, String secret)

The most basic implementation of the ApsalarConfig only requires the API Key and Secret. However, it is recommended that other configuration options be added to take advantage of all platform features. Below is a sample recommended implemen

ApsalarConfig config = new ApsalarConfig(apiKey, secretKey)
.withOpenURI(openURI) // pass URI from the intent here if your app supports deeplinks 
.withDDLHandler(new DeferredDeepLinkHandler() { ... }); // for deferred deeplinks

All Options for ApsalarConfig (Advanced):

withSessionTimeoutInSec(long timeout) //Session timeout in seconds
withLoggingEnabled() //To enable logging
withLogLevel(int level) //Default log level is Log.ERROR
withDDLHandler(DeferredDeepLinkHandler handler) // for deferred deeplinks
withDDLTimeoutInSec(long timeout)

Call Apsalar.init with ApsalarConfig:

Pass the config object you just created using ApsalarConfig.

protected void onCreate(Bundle savedInstanceState)
    //Other code

    //Init Apsalar SDK
    Apsalar.init(context, config); //context is Application Context

    //Other code

From Application class you can pass this or getApplicationContext() at the place of context

To get Application Context from inside activity you can call - currentActivity.getApplicationContext()

7. Session Management

The Apsalar SDK handles complete session management internally so no additional configuration required. Automatic session management is recommended, and requires Android API 14 (Ice Cream Sandwich or above).

Session length (timeout)

Session timeout are handled internally as well, where default timeout value is 60 Seconds.
To override default value you have to pass desired timeout (in seconds) to the method withSessionTimeoutInSec(seconds) in ApsalarConfig while initializing SDK. e.g. -

ApsalarConfig config = new ApsalarConfig(apiKey, secretKey)
.withSessionTimeoutInSec(120); //120 seconds (2 minutes) session timeout set

Manual Session handling (For Applications using Android API below 14)

In case if your Application’s minSdkVersion is below 14 (Targeting below ICE_CREAM_SANDWICH) then you have to manually manage Sessions by calling SDK’s two methods (onActivityResumed & onActivityPaused) accordingly from each of your activities like -

    protected void onResume() {
        .... //other code if any
    protected void onPause() {
        .... //other code if any
Note - In case you have custom common base activity class which is being derived in all other activities then you can place above calls of onActivityResumed & onActivityPaused to that common activity’s onResume & onPause method as well

8. Event Tracking

The first step is to decide which events you would like to track in your application. While there are a few restrictions on event and attribute names, you can generally use whichever names you prefer.

Once you’ve decided which events to track, you can begin implementing each event with the appropriate method like below:

Events Without Arguments

Apsalar.event(String eventName);

//An example login with no arguments    

Events With Arguments

Apsalar.event(String eventName, Object… args);

‘args’ must be one or more attribute/value pairs where the attribute is a string of the attribute’s name and the value is any of the allowable types( JSONObject value, i.e. JSONObject, JSONArray, String, Boolean, Integer, Long, Double or NULL). Please note, event arguments must exist as name-value pairs. If the args list contains an odd number of elements, then the name-value mapping is unbalanced and the event will be rejected by Apsalar’s servers.

// An example Purchase_Complete event passing quantity, product, and price
Apsalar.event("Purchase_Complete", "quantity", 3, "product", "cotton shirt", "price", 42.34);

Events With JSONObject Arguments

Apsalar.eventJSON(String name, JSONObject args);

‘args’ must be a JSONObject containing one or more attribute/value pairs where the attribute is a String that you have chosen as the attribute name and the value is any type allowable as a JSONObject value. Here is an example of these calls using a JSONObjects and JSONArrays to track shopping cart data:

import org.json.*

try {
  JSONArray contents = new JSONArray();
  JSONObject item1 = new JSONObject();

  item1.put("sku", "UPC-018627610014");
  item1.put("qty", 2);
  item1.put("unit_price", 8.99);
  item1.put("currency", "USD");

  JSONObject item2 = new JSONObject();
  item2.put("sku", "UPC-070271003758");
  item2.put("qty", 1);
  item2.put("unit_price", 15.99);
  item2.put("currency", "USD");

  JSONObject item3 = new JSONObject();
  item3.put("sku", "UPC-070271003758");
  item3.put("qty", 1);
  item3.put("unit_price", 15.99);
  item3.put("currency", "USD");

  JSONObject args = new JSONObject();
  args.put("contents", contents);
  args.put("total", 63.96);
  args.put("currency", "USD");
  args.put("member_id", "A556740089");

  // Record the event with Apsalar
  Apsalar.eventJSON("Purchase_Complete", args);
catch(JSONException e) {
  android.util.Log.e("Now", "JSON Exception in cart");

9. Revenue Tracking

Along with tracking standard events, revenue events can also be tracked in the Apsalar SDK via an explicit revenue event. Events should be tracked as revenue to enable revenue and LTV data to appear in reporting.

Apsalar.revenue(String currency, double amount);

Currency must be passed as a three-letter ISO 4217 currency code for correct tracking of revenue. E.g. “USD”, “EUR”, “INR”
An example of the revenue call is:

Apsalar.revenue("USD", 5.50);

Revenue Events with Product Details

Optionally, you can pass revenue data with product details for use in passing this data in postbacks, to partners

Apsalar.revenue(String currency, double amount, String productSKU, String productName, String productCategory, int productQuantity, double productPrice);

Currency must be passed as a three-letter ISO 4217 currency code for correct tracking of revenue. E.g. “USD”, “EUR”, “INR”

Apsalar.revenue("EUR", 5.00, "SKU1928375", "Reservation Fee", "Fee" , 1, 5.00);

10. Deferred Deep-linking

Set Callback Handler via ApsalarConfig

ApsalarConfig config = new ApsalarConfig(apiKey, secretKey);
//Callback handler, Note: handleLink() method will be invoked on UI (Main) Thread
config.withDDLHandler(new DeferredDeepLinkHandler() {
    public void handleLink(String link) {
        //Handle the deep link, which you configured on dashboard
config.withDDLTimeoutInSec(ddlTimeoutSec); //Optional, Timeout seconds, default is 60 seconds

With the help of withDDLTimeoutInSec method you can override the timeout seconds. After SDK initialization if callback is not received within that timeout duration, then SDK will not be calling this handler.

11. Uninstall Tracking

For all the steps to enable uninstall tracking, please see this guide here. This section only details the updates required for your app, to allow Apsalar to track your Android app’s uninstalls.

1. Incorporate Google Play Services

Uninstall tracking uses the services provided by the Google Cloud Messaging (GCM) platform. In order to integrate this service, ensure Google Play Services is included in your build. Follow Google’s instructions to include Google Play Services.

Please be aware of GCM requirements on supported Android versions:


GCM requires devices running Android 2.2 or higher that also have the Google Play Store application installed, or an emulator running Android 2.2 with Google APIs. Note that you are not limited to deploying your Android applications through Google Play Store.

However, if you want to continue to use new GCM features that are distributed through Google Play Services, the device must be running Android 2.3 or higher, or you can use an emulator running Android 2.3 with Google APIs.
On Android devices, GCM uses an existing connection for Google services. For pre-3.0 devices, this requires users to set up their Google accounts on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.

Users/devices who are not running on supported versions of Android will not be available for Apsalar uninstall tracking.

2. Update the AndroidManifest File

Update your AndroidManifest.xml file to add the necessary permissions for your app. The permissions required are the following (replace <your-package-name> with the your app’s package name. e.g. com.example.apsalar):

<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="" />

3. Register and Send the GCM Device Token

The last step is to set the GCM device token after your ApsalarConfig is initialized in the OnCreate()

Apsalar.setGCMDeviceToken(String gcmDeviceToken);

If you are already using GCM for push notifications in our app, simply provide the GCM device token already registered in your app through setGCMDeviceToken(). Please note that the GCM Sender ID used to generate the token should be the same one used on your app’s Application page.

Note - if your Application Does Not Yet Support GCM Push Notifications

If your app is not yet configured for GCM push notifications, you will need to enable push notifications first, and generate/retrieve the GCM device token to pass to the Apsalar SDK like above. There are a lot of documentation publicly available on guiding you through the process of enabling GCM push notifications for your app. We have provided Google’s documentation to get you started.

12. APK Preload Support

If you are building your app for the purposes preload campaigns, you can define these custom preload tags inside your Application’s manifest file with the following available keys:

For example:

            android:value="Marchv7" />
            android:value="1\ " /> <!-- Integer value 1-->
            android:value="Micromax" />

Note: Default values are expected to be in String form like "Marchv7" etc. In case you want to set numeric values then you have to declare them like "1\ " (Number followed by backslash and then a space).

13. Compile and Run

Compile and run your application to automatically register your application and events. User data should start populating on your dashboard within a few hours.
seconds ago
a minute ago
minutes ago
an hour ago
hours ago
a day ago
days ago
Invalid characters found