Skip to content
Track & Trigger - Android SDK Integration Guide
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
example-app Updated Android demo app to SDK Version 1.2.3 Oct 31, 2018
.gitignore Add .gitignore and examplea pp Jan 21, 2018
README.md Update README.md Apr 28, 2019
_config.yml Set theme jekyll-theme-slate Jan 22, 2018
changelog-2.0.md Update changelog-2.0.md Apr 29, 2019

README.md

Change Log v2.0 - April 2019

PLEASE READ new Android change log v2.0


Introduction

Marketers use the Optimove Relationship Marketing Hub to automate the execution of highly-personalized customer communications. Optimove offers its clients an efficient way to track data from their websites and trigger campaigns accordingly.

This guide will show you how to setup the Android SDK in order to:

  • Track visitor and customer actions and events
  • Trigger Realtime campaigns

Basic Setup

Request a Mobile SDK from Optimove

Before implementing the Optimove Track & Trigger to track visitor / customer activities or perform other functions (Optipush), you will need to contact your Optimove Customer Success Manager (CSM) or Optimove point of contact.

To get started, please follow the below instructions:

1. Pre-Requisites:

  1. The app's min (Android) SDK version is 19
  2. The Optimove Android SDK is dependent upon the Firebase Android SDK. If your application already uses Firebase SDK or has a dependency with Firebase SDK, a build conflict might occur, and even Runtime Exception, due to backwards compatibility issues.
    Therefore, it is highly recommended to match the application's Firebase SDK version to Optimove's Firebase SDK version as detailed in the following table.
Optimove SDK Version Firebase Core SDK Version Firebase Database SDK Version Firebase Messaging SDK Version Firebase Invites SDK Version Firebase Job Dispatcher SDK Version
1.3.0 16.0.6 16.0.5 17.3.4 16.0.6 0.8.5
  1. Optimove's Android SDK is written in Java 8. Hosting apps that are written in Java 7 or use Jack some build errors may occur. In that case migrate the app to Java 8.

For more information about Android Official Java 8 Support checkout this Developer's Guide article

Add the following to the app module's build.gradle file, under the android object.

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

Kotlin Support

Since Kotlin is completely interoperable with Java Apps that are written in Kotlin can use the SDK. However, these apps should add the formentioned compileOptions and also following object below:

kotlinOptions {
    jvmTarget = '1.8'
}

If you get an error like :app:transformClassesWithDesugarForDebug, you may have to enable desugaring in your gradle.properties file:

android.enableD8.desugaring = true

2. Provide your Android app details:

Send the following information to your CSM or Optimove POC with your request for your Mobile SDK configuration details in order to incorporate into your Android app :

  1. App's package(s) (If you are using multiple apps for development/testing purposes, please provide a list of all package names being used for all environments.)
  2. SHA256 cert fingerprint (can be retrieved using: keytool -list -v -keystore my-release-key.keystore)

3. Retrieve tenant_information_suite details:

After providing the info above, you will receive a tenant_information_suite from the Optimove Product Integration Team that contains:

  1. End-point URL – The URL where the tenant configurations reside
  2. Unique Optimove token – The actual token, unique per tenant
  3. Configuration name – The version of the desired configuration

For a demo application containing the Android SDK, please use our Android GitHub repository.

Setting Up the Android SDK

1. Add the Optimove Repository to Your Project

  1. Open the project's build.gradle file (located under the application's root folder).
  2. Under allprojects, locate the repositories object.
  3. Add the optimove-sdk repository:
maven {
  url  "https://mobiussolutionsltd.bintray.com/optimove-sdk"
}

2. Download the SDK

  1. Open the app's build.gradle file (located under the application's app module folder).
  2. Under dependencies, add the following:
implementation 'com.optimove.sdk:optimove-sdk:1.3.0'

3. Run the SDK

The Optimove SDK automatically initializes itself when the application process is started. To pass it the tenant info set BuildConfigs in the gradle build script of the App module. You can use build flavours to set the appropriate environment of the SDK to the appropriate build type.

android {
    buildTypes {
        debug {
            // Optimove SDK Integration: Don't delete the single nor the double quote - just the value with the enclosing diamond brackets
            buildConfigField "String", "OPTIMOVE_INIT_ENDPOINT_URL", '"<STAGING_VALUE_PROVIDED_BY_OPTIMOVE>"'
            buildConfigField "String", "OPTIMOVE_TOKEN", '"<STAGING_VALUE_PROVIDED_BY_OPTIMOVE>"'
            buildConfigField "String", "OPTIMOVE_CONFIG_NAME", '"<STAGING_VALUE_PROVIDED_BY_OPTIMOVE>"'
            buildConfigField "Boolean", "OPTIMOVE_HAS_DEFAULT_FIREBASE_APP", "<STAGING_VALUE_PROVIDED_BY_OPTIMOVE>" // Set to true if your app uses the Firebase SDK already
        }
        release {
            // Optimove SDK Integration: Don't delete the single nor the double quote - just the value with the enclosing diamond brackets
            buildConfigField "String", "OPTIMOVE_INIT_ENDPOINT_URL", '"<PRODUCTION_VALUE_PROVIDED_BY_OPTIMOVE>"'
            buildConfigField "String", "OPTIMOVE_TOKEN", '"<PRODUCTION_VALUE_PROVIDED_BY_OPTIMOVE>"'
            buildConfigField "String", "OPTIMOVE_CONFIG_NAME", '"<PRODUCTION_VALUE_PROVIDED_BY_OPTIMOVE>"'
            buildConfigField "Boolean", "OPTIMOVE_HAS_DEFAULT_FIREBASE_APP", "<PRODUCTION_VALUE_PROVIDED_BY_OPTIMOVE>" // Set to true if your app uses the Firebase SDK already, false otherwise
        }
    }
}

4. Important Installation and Usage Notes

  1. Working with multiple Firebase messaging services (Hosting application uses Firebase)

Multiple FirebaseMessagingServices:

When the hosting app also utilizes Firebase Cloud Messaging and implements the FirebaseMessagingService Android's Service Priority kicks in, and Optimove SDK's own FirebaseMessagingService is never called. For that reason, the hosting app must call explicitly Optimove's onMessageReceived and onTokenRefresh callbacks.
The onMessageReceived method returns true if the push message was intended for the Optimove SDK.

public class MyMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
      super.onMessageReceived(remoteMessage);
      boolean wasOptipushMessage = new OptipushMessagingHandler(this).onMessageReceived(remoteMessage);
      if (wasOptipushMessage) {
        // You should not attempt to present a notification at this point.
        return;
      }
      // The notification was meant for the App, perform your push logic here
    }
    
    @Override
    public void onNewToken(String s) {
      super.onNewToken(s);
      // Forward the call to the Optimove SDK
      new FcmTokenHandler().onTokenRefresh();
      // Continue with the application logic
    }
}


FirebaseApp Initialization Order

Usually when using Firebase it takes care of its own initialization. However, if you desire to initialize the default FirebaseApp manually. In these special cases, be advised that the SDK's automatic initialization flow assumes that if you have a default FirebaseApp you've already called FirebaseApp.initializeApp() (manually). The SDK knows to handle the aforementioned failure gracefully, however, for it to properly work, make sure you call Optimove.connectToOptimoveFirebaseApp() as soon as you've called FirebaseApp.initializeApp() manually (automatic initialization is automatically handled by the SDK).

Firebase guidelines require you to initialize the FirebaseApp instance ASAP. That means either a custom ContentProvider or Application subclass. Optimove cannot support the outcomes of initializing the FirebaseApp instance outside of these objects (like in the Activity instance). For more info read this Firebase blog post.


  1. State Registration:

The SDK initialization process occurs asynchronously, off the Main UI Thread.
Before calling the Public API methods, make sure that the SDK has finished initialization by calling the registerSuccessStateListener function with an instance of OptimoveSuccessStateListener.

If the object implementing the OptimoveSuccessStateListener is a component with a "Lifecycle" (i.e. Activity or Fragment), always unregister that object at the onStop() callback to prevent memory leaks.

public class MainActivity extends AppCompatActivity implements OptimoveSuccessStateListener {

  @Override
  protected void onStart() {

    super.onStart();
    Optimove.registerSuccessStateListener(this);
  }

  @Override
  protected void onStop() {

    super.onStop();
    Optimove.unregisterSuccessStateListener(this);
  }

  @Override
  public void onConfigurationSucceed(SdkRequiredPermission... missingPermissions) {
    //If appropriate, ask for permissions here
    //Do any call to the Optimove SDK safely from here on out
  }
}

  1. Missing Optional Permissions:

Once the SDK has finished initializing successfully, it passes all User Dependent missing permissions through the onConfigurationSucceed(SdkRequiredPermission... missingPermissions). These permissions are important to the user experience but do not block the SDK's proper operation.
These Permission are:

  • DRAW_NOTIFICATION_OVERLAY - Indicates that the app is not allowed to display a "drop down" notification banner when a new notification arrives.
  • NOTIFICATIONS - Indicates that the user has opted-out from the app's notification
  • GOOGLE_PLAY_SERVICES - Indicates that the Google Play Services app on the user's device is either missing or outdated
  • ADVERTISING_ID - Indicates that the user has opted-out from allowing apps from accessing his/her Advertising ID
  1. The Hosting Application Specifies Rules for Automatic Backup

Starting from API 23 Android offers the Auto Backup for Apps feature as a way to back up and restore the user's data in the app. The Optimove SDK depends on some local files being deleted once the app is uninstalled.
For that reason if the hosting app also defines android:fullBackupContent="@xml/app_backup_rules" in the manifest.xml file, Android will raise a merge conflict.

Follow these steps to resolve the conflict and maintain the data integrity of the Optimove SDK:

  1. Add tools:replace="android:fullBackupContent"> to the application tag
  2. Copy the content of the optimove_backup_rules.xml to your full-backup-content xml.

For more information about Android Automatic Backup checkout this Developer's Guide article


5. Tracking Visitor and Customer activity

You will also need to include the following steps to complete the basic setup:


Advanced Setup

Use the Advanced Setup (optional) in order to track visitor and customer customized actions and events. As described in Tracking Custom Events, this step requires collaboration between you and Optimove's Integration Team. Please contact your Optimove Customer Success Manager (CSM) or Optimove point of contact to schedule a meeting with the Product Integration team.

Note: You can deploy the basic setup, followed by adding the advanced setup at a later stage. The Basic Setup is a pre-requisite.


Track

Linking App Visitors to Registered User IDs

Once the user has downloaded the application and the OptimoveSDK for Android has run for the first time, the user is considered a visitor, i.e., an unidentified person.

Once the user authenticates and becomes identified by a known PublicCustomerId, then the user is considered a customer. As soon as this happens for each individual user, call the SetUserId function to pass the CustomerId to the Optimove singleton:

// Call to notify the SDK that the user has a known PublicCustomerId
Optimove.getInstance().setUserId("a-unique-user-id");
  • The CustomerId is usually provided by the server application that manages customers, and is the same ID provided to Optimove during the daily customer data transfer.
  • Any userId that does not correspond to your Optimove unique identifier (Customer ID) due to faulty / unrecognized userIds will now be excluded from your customer tracked activity. Therefore please make surethat the userId sent via the userId is a recognizable ID.
  • Due to its high importance, setUserId may be called at any time, regardless of the SDK's state
  • If you will be sending encrypted userId, please follow the steps in Reporting encrypted CustomerIDs

Tracking Screen Visits

To track which screens the user has visited in your app, call the reportScreenVisit method of the Optimove singleton. It can accept either the current Activity or, for more finely tuned screen hierarchy reporting, a String describing the Screen's hierarchy.

public class MainActivity extends AppCompatActivity {
  
  @Override
  public void onConfigurationSucceed(SdkRequiredPermission... missingPermissions) {

    Optimove.getInstance().reportScreenVisit(this, "Main");
  }
}
public class CheckoutFragment extends Fragment {

  @Override
  public void onConfigurationSucceed(SdkRequiredPermission... missingPermissions) {

    Optimove.getInstance().reportScreenVisit("Main/Footwear/Boots/ConfirmOrder", "Checkout");
  }
}

Tracking/Updating User Email Addresses

To track a user's email address, such as when a visitor enters the app and submits a register or subscribe form, call the setUserEmail method to record the address. This is best used when you want to capture realtime email event.

// Call to notify the SDK that the user has a known email address. Can be called regardless of the "setUserId" call.
Optimove.getInstance().setUserEmail("a.valid@email.com");

In instances where you need to set both the visitor's user ID and email address simultaneously, you should use the registerUser method instead of setUserEmail. This applies to all situations in which a single user action requires you to set both the user ID and email address (e.g., registration, newsletter signup).


Registering the User ID and User Email at the Same Time

In all situations where a single user action requires you to set both the customer ID and email address (e.g., registration, newsletter signup) simultaneously, you should use the registerUser method (instead of calling both setUserId and setUserEmail) to ensure the proper registration of the user in Optimove.

// Convenience method to call both "setUserId" and "setEmail" simultaneously.
Optimove.getInstance().registerUser("a-unique-user-id", "a.valid@email.com");

Tracking Custom Events

Optimove clients may use the Optimove Mobile SDK to track specific customer actions and other custom events to Optimove (beyond the OOTB events such as visits). This data is used for tracking visitor and customer behavior, targeting campaigns to specific visitor and/or customer segments and triggering campaigns based on particular visitor and/or customer actions/events.

To see examples of Custom Events, please visit Defining the Set of Custom Tracking Events that You Will Report for more information.

Note: While you can always add/change the custom events and parameters at a later date (by speaking with the Optimove Product Integration Team), only the particular custom events that you and the Optimove Product Integration Team have already defined together will be supported by your Optimove site.

How to Track a Custom Event from within your Android app

Once you and the Optimove Integration Team have together defined the custom events supported by your app, the Integration Team will implement your particular functions within your Optimove site, while you will be responsible for passing the information of the individual events within your app using the appropriate function calls.

There are 2 ways to report a Custom Event through the Optimove SDK:

1. For simple events

Pass the the custom event's name and parameters directly via the Optimove.getInstance().reportEvent(String name, Map<String, Object> parameters) method.

public class MainActivity extends AppCompatActivity implements OptimoveStateListener {

  public void onClick(View view) {
    Map<String, Object> params = new HashMap<>();
    params.put("my_param_1", 42);
    Optimove.getInstance().reportEvent("my_custom_event", params);
  }
}

2. For more complex events

The Optimove SDK defines an interface called OptimoveEvent. It defines two methods:

  1. String getName() – Declares the custom event's name
  2. `Map<String, Object> getParameters()** – Specifies the custom event's parameters.

Use this interface to conform your complex event objects to the Optimove format and pass it to the SDK via the Optimove.getInstance().reportEvent(OptimoveEvent optimoveEvent) method.

public class MainActivity extends AppCompatActivity implements OptimoveStateListener {

  public void onClick(View view) {
    Optimove.getInstance().reportEvent(new MyCustomEvent(42, "towel"));
  }
}


class MyCustomEvent implements OptimoveEvent {

  private int prizeValue;
  private String itemOfInterest;

  public MyCustomEvent(int prizeValue, String itemOfInterest) {
    this.prizeValue = prizeValue;
    this.itemOfInterest = itemOfInterest;
  }

  @Override
  public String getName() {
    return "my_custom_event";
  }

  @Override
  public Map<String, Object> getParameters() {
    Map<String, Object> params = new HashMap<>();
    params.put("prize_value", prizeValue);
    params.put("item_of_interest", itemOfInterest);
    return params;
  }
}

  • As already mentioned, all custom events must be pre-defined in your Tenant configurations by the Optimove Integration Team.
  • Reporting of custom events is only supported if you have the Mobile SDK implemented.
  • Events use snake_case as a naming convention. Separate each word with one underscore character (_) and no spaces. (e.g., Checkout_Completed)

Trigger

Executing via Optimail

Ability to execute campaigns using Optimove's Optimail email service provider (ESP) add-on product. With Optimail you will be able to:

  • Send HTML email campaigns
  • Set personalized tags (first name, last name, and more)
  • These Tags are retrieved from both your daily data transfer, as well as the SDK events you are tracking.
  • Preview campaign email before sending
  • Send realtime marketing campaigns based on your website SDK activity triggering rules

For more information on how to add Optimail to your account, please contact your CSM or your Optimove point of contact.

Executing via Optimove APIs

You can also trigger Optimove realtime campaigns using Optimove's APIs:

  • Register listener to receive realtime campaign notifications, please refer to RegisterEventListener (where eventid = 11)
  • To view your realtime API payload, please refer to Optimove Realtime Execution Channels (see Method 3: Realtime API) For more information on how to acquire an API key to use Optimove APIs, please request one from your CSM or your Optimove point of contact.
You can’t perform that action at this time.