Support Center

Integrating the Android SDK

Last Updated: Oct 01, 2014 10:06AM 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:
  • If you are upgrading from a previous version of the Android 4.X.X SDK, please use this upgrade guide.
  • Apsalar's latest Android SDKs, 6.X.X, supports Android 2.2 (Froyo) and higher; please be sure you're using a compatible version of Android's framework for your application.
    • Starting August 1, 2014, Google is advising the use of the new Android Advertising ID for tracking and marketing purposes. While Apsalar's latest SDK may be compatible with Android versions lower than 2.2, it will not be able to utilize Android's new Advertising ID. 
    • Apsalar’s SDK will report using the new Android Advertising ID for devices using PlayStore v4. Older devices will continue to report using the ANDI.
    • Please note, use of the 6.X.X SDK has not been tested with Android versions lower than 2.2. Should you choose to use the 6.X.X SDK with an Android version lower than 2.2, 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 other necessary libraries into your application

4. Add Necessary Permissions to your Applications 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
    • Add the following to your manifest tag:
      <uses-permission android:name="android.permission.INTERNET" />
  • ACCESS_NETWORK_STATE - Required
    • Add the following to your manifest tag:
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • WRITE_EXTERNAL_STORAGE - Required
    • Add the following to your manifest tag:
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  • READ_PHONE_STATE - Optional
    • Allows the capturing of IMEI device ID
    • Add the following to your manifest tag:
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />

5. Add an Apsalar Compatible Receiver

The Android 6.X.X SDK offers two Receiver options: default and custom. The default receiver solution is best for most applications. If you're utilizing your application's receiver for internal purposes or use with other 3rd parties, than the custom receiver may better fit your needs.

To implement the default receiver:

  • Add the following to your <application> tag in your manifest file:
    <receiver android:exported="true" android:name="com.apsalar.sdk.ApsalarReceiver">
          <intent-filter>
               <action android:name="com.android.vending.INSTALL_REFERRER"></action>
               <action android:name="com.apsalar.sdk.SOFT_RESET"></action>
          </intent-filter>
    </receiver>
  • With Apsalar's latest SDK memory leaks with your apps's broadcast receiver can be avoided by unregistering it when your app exits. To support this change, an adjustment to your Activity's onDestroy() method is necessary. You'll need to either overwrite your Activity's onDestroy() method with the following or add it your existing modification of the onDestroy() method:
    @Override
    protected void onDestroy() {
        try {
             Apsalar.unregisterApsalarReceiver();
        }
        catch (Exception e) {
             ;
        }
        super.onDestroy();
    }
  • Here is sample AndroidManifest.xml file configured with the default receiver:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.apsalar.android.SampleActivity"
        android:versionCode="1"
        android:versionName="1.0">
    
        
      <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="19" />
    
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
     
      <application android:label="@string/app_name" android:icon="@drawable/icon" android:allowBackup="true">
        
        <activity android:name="SampleActivity"
            android:label="@string/app_name">
    
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
    
          <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="http"
                  android:host="qa5.apsalar.com"
                  android:pathPrefix="/api/v1/appstore/com.apsalar.android.SampleActivity" />
          </intent-filter>
        </activity>
    
        <meta-data android:name="com.google.android.gms.version"
                   android:value="@integer/google_play_services_version"/>
                   
        <activity
                android:name="com.google.android.gms.ads.AdActivity" >
                android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        </activity>    
              
        <receiver android:exported="true" android:name="com.apsalar.sdk.ApsalarReceiver">
          <intent-filter>
               <action android:name="com.android.vending.INSTALL_REFERRER"></action>
               <action android:name="com.apsalar.sdk.SOFT_RESET"></action>
          </intent-filter>
        </receiver>
    
      </application>
    </manifest>

To implement the custom receiver:

  • Add the following to your manifest file with the other permission entries:
    <permission
        android:name="com.apsalar.android.APSALAR_PERMISSION"
        android:protectionLevel="normal" />
    
  • Define your custom receiver class using the following code and adding your existing receiver code where indicated, if applicable. Please note, you must use the 'SafeApsalarReceiver' name for the subclass:
    import java.io.UnsupportedEncodingException
    import java.net.URLDecoder
    import android.content.Context
    import android.content.Intent
    import android.os.Bundle
    import android.util.Log
    import com.apsalar.sdk.ApsalarReceiver
    
    public class SafeApsalarReceiver extends ApsalarReceiver {
    
        @Override
        public void onReceive(Context ctx, Intent intent) {
            super.onReceive(ctx, intent); //handle apsalar call for the install
            Bundle extras = intent.getExtras();
            if (extras == null) {
                return;
            }
            String referrer = extras.getString("referrer");
            if (referrer == null || referrer.length() == 0) {
                return;
            }
            try {
                referrer = URLDecoder.decode(referrer,"UTF-8");
            }
            catch (UnsupportedEncodingException e) {
                return;
            }
    
            //------------------------------
            // put custom receiver code here
            //------------------------------
    
        }
    
    }
  • Replace the default receiver inside your <application> section with the receiver below, modifying your existing receiver if necessary. The receiver should be the last item in your application tag. Please note the domain for the receiver must match the domain of your package:
    <receiver android:exported="true"
        android:name="com.yourDomainHere.SafeApsalarReceiver"
        android:permission="com.apsalar.android.APSALAR_PERMISSION">
      <intent-filter>
           <action android:name="com.android.vending.INSTALL_REFERRER"></action>
           <action android:name="com.apsalar.sdk.SOFT_RESET"></action>
      </intent-filter>
    </receiver>
  • Create or register the custom receiver, as well as unregister it.  The skeleton Activity below shows
    how to setup and take-down a custom broadcast receiver.
    import com.apsalar.sdk.SafeApsalarReceiver;
    import com.apsalar.sdk.Apsalar;
    public class SampleActivity extends Activity
    {
        private static String BROADCAST_ACTION = "com.android.vending.INSTALL_REFERRER";
        private static SafeApsalarReceiver sar;
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            // normal initialization of Activity
            // setup the custom Apsalar receiver
            IntentFilter filter = new IntentFilter();
            filter.addAction(BROADCAST_ACTION);
            sar = new SafeApsalarReceiver();
            registerReceiver(sar, filter);
        }
    
        @Override
        protected void onDestroy() {
            try { 
                 Apsalar.unregisterApsalarReceiver();
                 unregisterReceiver(sar);
            }
            catch (Exception e) {
                 ;
            }
            super.onDestroy();
        }
    }
    

5. Set your Facebook App ID (Optional)

In order to track Facebook attributions for your application, you must set your Facebook App ID. Your Facebook App ID is s a 15 digit number unique to you as a developer on Facebook's platform. If you do not plan to track Facebook attributions, you may skip this step.

Please note, your Facebook App ID must be set in your application prior to initializing a session with Apsalar's SDK. To set your Facebook App ID, use the following call:
Apsalar.setFBAppId("Your_Facebook_App_ID");

6. Start an Apsalar session

To properly track events for your application and accurately monitor session lengths, an Apsalar session must be initiated when the user launches the application. Use the following steps to initialize an Apsalar session:
  • Import the Apsalar class libraries to your main activity with the following:
    import com.apsalar.sdk.Apsalar;
  • Add the startSession call to the onCreate() method of your main activity using your Apsalar API key and secret. Your API Key and secret can be obtained from the Get the SDK page on your account:
    Apsalar.startSession(currentActivity, "Your_Api_Key", "Your_Secret");

7. Start Tracking Events

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. To help you decide which events and attributes to track, we have compiled a set of best practices.

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

For Revenue Events

We offer different solutions based on how much detail you'd like to track for your Revenue events. Please see our guide for configuring revenue events for more specific information.

Events Without Arguments

Apsalar.event(String eventName);
//Example call
Apsalar.event("Purchase_Complete");

Events With Arguments

Apsalar.event(String eventName, Object... args);
//Example call
Apsalar.event("Purchase_Complete", "quantity", 3, "product", "cotton shirt", "price", 42.34);
'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.

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");
  contents.put(item1);

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

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

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

8. End an Apsalar Session

Apsalar encourages ending the session when a user quits the application. To end a session, use the following method:
Apsalar.endSession()

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

Note: Event attributes will populate with some delay, after Apsalar batch reports are run.

Optional Android 6.X.X Features

The following items are additional features and options available in Apsalar's 6.X.X Android SDK.

Control Heartbeat

Apsalar’s Android SDK sends a heartbeat to Apsalar servers at a responsible rate to properly track session lengths and dequeue events that are collected during offline operation.. The heartbeat starts after 5 minutes and remains active until session end. The time to between subsequent heartbeats is doubled after each heartbeat until it reaches at a maximum of 6 hours, ensuring minimal network usage.

However, some app developers need fine control over a device’s network connections and to meet this need, our Android API provides two methods to control heartbeat:
boolean Apsalar.isHeartbeatEnabled() // Returns true if enabled, false if disabled
boolean Apsalar.enableHeartbeat(boolean) // Use true to enable, false to disable

Age and Gender

In Apsalar's continued effort to provide with thorough insight into how your application's are being utilized, we've provided two methods to set the age and gender for users. Currently, we do not report this data in our UI, but we hope to develop this feature in the future. You can begin passing this information and the historical data will be available to you when these dimensions are added to Apsalar's reporting. To set age and gender, please use the following methods:
Apsalar.setAge(int age); // Where age is integer between 0 and 100
Apsalar.setGender(String gender); // Where gender is either 'f' or 'm'
support@apsalar.com
http://assets03.desk.com/
apsalarinc
Loading
seconds ago
a minute ago
minutes ago
an hour ago
hours ago
a day ago
days ago
about
Invalid characters found
/customer/en/portal/articles/autocomplete