Android SDK Integration Guide
This page explains how to implement the Android SDK for Rokt Ads to deliver more relevant customer experiences at checkout. The SDK allows you to trigger and track these experiences (like displaying offers on confirmation pages) by firing on configured pages and passing user and transaction data back to Rokt for personalization and measurement.
Your dedicated account representative will help configure your account for the Android SDK. They will provide you with both the key and secret required to initialize the SDK and additional resources needed to render the most relevant experiences for your customers.
These instructions require development resources to complete. If you require additional assistance, please reach out to your Rokt account manager.
1. Add dependencies
Update your gradle file to include the necessary dependencies for the SDK:
- build.gradle.kts
- build.gradle
dependencies {
implementation("com.mparticle:android-rokt-kit:5.74.0")
implementation("com.mparticle:android-core:5.74.0")
}
dependencies {
implementation "com.mparticle:android-rokt-kit:5.74.0"
implementation "com.mparticle:android-core:5.74.0"
}
2. Initialize the SDK in your app
The Android SDK can be configured using an MParticleOptions
object and a builder class in the onCreate()
of the Application
class. The mParticle Android SDK should be initialized before any other SDK API calls are made.
Make sure to replace your-key
and your-secret
in the above code sample with the key and secret provided by your dedicated Rokt account representative.
- Kotlin
- Java
import com.mparticle.MParticle
import com.mparticle.MParticleOptions
class YourApplicationClass : Application() {
override fun onCreate() {
super.onCreate()
// Identify the current user:
// If you do not have the user's email address, you can pass in a null value
val identifyRequest = IdentityApiRequest.withEmptyUser()
// If you're using an un-hashed email address, set it in 'email'.
.email("j.smith@example.com")
.build()
// If the user is identified with their email address, set additional user attributes.
val identifyTask = BaseIdentityTask()
.addSuccessListener { identityApiResult ->
val user = identityApiResult.user
user.setUserAttribute("example attribute key", "example attribute value")
}
val options: MParticleOptions = MParticleOptions.builder(this)
.credentials(
"your-key", // The key provided by your Rokt account representative
"your-secret" // The secret provided by your Rokt account representative
).environment(MParticle.Environment.Development) // Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
.build()
MParticle.start(options)
}
}
import com.mparticle.MParticle;
import com.mparticle.MParticleOptions;
public class YourApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
MParticleOptions options = MParticleOptions.builder(this)
.configuration(kitOptions)
.credentials(
"your-key", // The key provided by your Rokt account representative
"your-secret" // The secret provided by your Rokt account representative
).environment(MParticle.Environment.Production).build(); // Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
// Identify the current user:
IdentityApiRequest identifyRequest = IdentityApiRequest.withEmptyUser()
// If you do not have the user's email address, you can pass in a null value
.email("j.smith@example.com").build();
// If the user is identified with their email address, set additional user attributes.
BaseIdentityTask identifyTask = new BaseIdentityTask()
.addSuccessListener(new TaskSuccessListener() {
@Override
public void onSuccess(IdentityApiResult identityApiResult) {
MParticleUser user = identityApiResult.getUser();
user.setUserAttribute("example attribute key", "example attribute value");
}
});
MParticle.start(options);
}
}
Make sure to replace your-key
and your-secret
in the above code sample with the key and secret provided by your dedicated Rokt account representative.
Identify the user
When the SDK is initialized, it can identify the current user so that any collected data is correctly attributed to them and to ensure they are shown the most relevant ads based on their behavior.
The SDK initialization script includes an object called identifyRequest:
- Kotlin
- Java
val identifyRequest = IdentityApiRequest.withEmptyUser()
.email("j.smith@example.com")
.build()
IdentityApiRequest identifyRequest = IdentityApiRequest.withEmptyUser()
.email("j.smith@example.com")
.build();
Within identifyRequest
, pass the user’s email address into the email
field.
Set additional user attributes
The initialization script includes a callback function that allows you to set additional user attributes for the user if they are successfully identified with their email address:
- Kotlin
- Java
val identifyTask = BaseIdentityTask()
.addSuccessListener { identityApiResult ->
val user = identityApiResult.user
user.setUserAttribute("example attribute key", "example attribute value")
}
BaseIdentityTask identifyTask = new BaseIdentityTask()
.addSuccessListener(new TaskSuccessListener() {
@Override
public void onSuccess(IdentityApiResult identityApiResult) {
MParticleUser user = identityApiResult.getUser();
user.setUserAttribute("example attribute key", "example attribute value");
}
});
3. Identify the user
Whenever the user provides their email address after the SDK has initialized (for example, when they log in or make a purchase), you should call the identify method to pass their email to Rokt. This ensures that data is correctly attributed to the current user.
3.1 Create an identifyRequest
To identify the user, first create an identifyRequest
object to contain the user’s email address.
If you are providing an un-hashed email address, use:
- Kotlin
- Java
val identifyRequest = IdentityApiRequest.withEmptyUser()
.email("j.smith@example.com")
.build()
IdentityApiRequest identifyRequest = IdentityApiRequest.withEmptyUser()
.email("j.smith@example.com")
.build();
3.2 Set additional user attributes
Next, you have the option of setting additional user attributes when identifying a user by creating a callback function. If the identifyRequest
succeeds, then the user attributes you set with setUserAttribute
are assigned to the user.
- Kotlin
- Java
val identifyTask = BaseIdentityTask()
.addSuccessListener { identityApiResult ->
val user = identityApiResult.user
user.setUserAttribute("example attribute key", "example attribute value")
}
BaseIdentityTask identifyTask = new BaseIdentityTask()
.addSuccessListener(new TaskSuccessListener() {
@Override
public void onSuccess(IdentityApiResult identityApiResult) {
MParticleUser user = identityApiResult.getUser();
user.setUserAttribute("example attribute key", "example attribute value");
}
});
3.3 Call the identify method
Finally, after creating your identifyRequest
and your identityCallback
, to set any additional attributes, call the identify method, passing in the identifyRequest
and identityCallback
objects you just created:
- Kotlin
- Java
MParticle.getInstance()?.Identity()?.identify(identifyRequest)
MParticle.getInstance().Identity().identify(identifyRequest);
For example, to identify a user named Jane Smith with the email address j.smith@example.com (and you don't need to hash their email address) you would use:
- Kotlin
- Kotlin
val identifyRequest = IdentityApiRequest.withEmptyUser()
.email("j.smith@example.com")
.build()
val identifyTask = BaseIdentityTask()
.addSuccessListener { identityApiResult ->
val user = identityApiResult.user
user.setUserAttribute("example attribute key", "example attribute value")
}
MParticle.getInstance()?.Identity()?.identify(identifyRequest)
IdentityApiRequest identifyRequest = IdentityApiRequest.withEmptyUser()
.email("j.smith@example.com")
.build();
BaseIdentityTask identifyTask = new BaseIdentityTask()
.addSuccessListener(new TaskSuccessListener() {
@Override
public void onSuccess(IdentityApiResult identityApiResult) {
MParticleUser user = identityApiResult.getUser();
user.setUserAttribute("example attribute key", "example attribute value");
}
});
MParticle.getInstance().Identity().identify(identifyRequest);
4. Track User Attributes
You can use the Rokt SDK to collect user attributes separately from events. User attributes are separate from custom attributes when tracking events. The SDK will associate any user attributes collected in a given session with events triggered in the same session.
To collect user attributes, the following code should be run in your app immediately after initializing the Rokt SDK, and before you log an event.
- Kotlin
- Java
import com.mparticle.MParticle
// Retrieve the current user. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
val currentUser = MParticle.getInstance()?.Identity()?.currentUser
// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
currentUser?.setUserAttribute("custom-attribute-name", "custom-attribute-value")
// Note: all user attributes (including list attributes and tags) must have distinct names.
// Rokt recommends setting as many of the following user attributes as possible:
currentUser?.setUserAttribute("firstname", "John")
currentUser?.setUserAttribute("lastname", "Doe")
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser?.setUserAttribute("mobile", "3125551515")
currentUser?.setUserAttribute("age", "33")
currentUser?.setUserAttribute("gender", "M")
currentUser?.setUserAttribute("city", "Brooklyn")
currentUser?.setUserAttribute("state", "NY")
currentUser?.setUserAttribute("zip", "123456")
currentUser?.setUserAttribute("dob", "yyyymmdd")
currentUser?.setUserAttribute("title", "Mr")
currentUser?.setUserAttribute("language", "en")
currentUser?.setUserAttribute("value", "52.25")
currentUser?.setUserAttribute("predictedltv", "136.23")
// You can create a user attribute to contain a list of values
val attributeList = ArrayList<String>()
attributeList.add("documentary")
attributeList.add("comedy")
attributeList.add("romance")
attributeList.add("drama")
currentUser?.setUserAttributeList("favorite-genres", attributeList)
// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser?.removeUserAttribute("attribute-to-remove")
import com.mparticle.MParticle;
import com.mparticle.MParticleUser;
// Retrieve the current user. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
MParticleUser currentUser = MParticle.getInstance().Identity().getCurrentUser();
// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
currentUser.setUserAttribute("custom-attribute-name", "custom-attribute-value");
// Note: all user attributes (including list attributes and tags) must have distinct names.
// Rokt recommends setting as many of the following user attributes as possible:
currentUser.setUserAttribute("firstname", "John");
currentUser.setUserAttribute("lastname", "Doe");
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser.setUserAttribute("mobile", "3125551515");
currentUser.setUserAttribute("age", "33");
currentUser.setUserAttribute("gender", "M");
currentUser.setUserAttribute("city", "Brooklyn");
currentUser.setUserAttribute("state", "NY");
currentUser.setUserAttribute("zip", "123456");
currentUser.setUserAttribute("dob", "yyyymmdd");
currentUser.setUserAttribute("title", "Mr");
currentUser.setUserAttribute("language", "en");
currentUser.setUserAttribute("value", "52.25");
currentUser.setUserAttribute("predictedltv", "136.23");
// You can create a user attribute to contain a list of values
List<String> attributeList = new ArrayList<>();
attributeList.add("documentary");
attributeList.add("comedy");
attributeList.add("romance");
attributeList.add("drama");
currentUser.setUserAttributeList("favorite-genres", attributeList);
// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser.removeUserAttribute("attribute-to-remove");
5. Capture Screen Views
One of the most basic event types you can track is the screen view. To log a screen view, call the MParticle.getInstance().logScreen()
method as soon as the screen loads, passing in the name of the screen as a string and an optional hash map containing any descriptive attributes.
The name you pass in should be one of a limited set of screens, like 'homepage'
or 'product detail page'
.
- Kotlin
- Java
import com.mparticle.MParticle
val screenInfo = HashMap<String, String>()
screenInfo["rating"] = "5"
screenInfo["property_type"] = "hotel"
MParticle.getInstance()?.logScreen("Details", screenInfo)
import com.mparticle.MParticle;
HashMap<String, String> screenInfo = new HashMap<>();
screenInfo.put("rating", "5");
screenInfo.put("property_type", "hotel");
if (MParticle.getInstance() != null) {
MParticle.getInstance().logScreen("Details", screenInfo);
}
6. Track Conversions
To track a conversion, run the following code snippet on the most appropriate page that's loaded after a customer converts, such as a purchase confirmation or "thank you" page.
When pasting the code snippet into your site, make sure to:
- Replace the sample user attributes in the
setUserAttribute
calls the actual values for your user or customer. Rokt recommends setting at least the following user attributes:firstname
lastname
zipcode
mobile
- Replace the sample conversion event attributes with with actual values from your conversion event.
When logging a conversion event, you should include as many user attributes and event attributes as possible to improve Rokt's ability to optimize your campaigns.
- Kotlin
- Java
MParticleUser currentUser = MParticle.getInstance().Identity().getCurrentUser();
currentUser.setUserAttribute("firstname", "John");
currentUser.setUserAttribute("lastname", "Doe");
currentUser.setUserAttribute("mobile", "3125551515");
currentUser.setUserAttribute("zip", "98103");
val customAttributes = mapOf(
"conversiontype" to "signup", // type of conversion
"confirmationref" to "54321", // Transaction ID / Order ID
"amount" to "", // Transaction amount e.g. 300.5
"currency" to "", // Transaction currency e.g. USD
// You can track your own custom event attributes!
"CUSTOM_EVENT_ATTRIBUTE_NAME" to "CUSTOM_EVENT_ATTRIBUTE_VALUE"
)
val event = MPEvent.Builder("conversion", MParticle.EventType.Transaction)
.customAttributes(customAttributes)
.build()
MParticle.getInstance()?.logEvent(event)
MParticleUser currentUser = MParticle.getInstance().Identity().getCurrentUser();
currentUser.setUserAttribute("firstname", "John");
currentUser.setUserAttribute("lastname", "Doe");
currentUser.setUserAttribute("mobile", "3125551515");
currentUser.setUserAttribute("zip", "98103");
Map<String, String> customAttributes = new HashMap<String, String>();
customAttributes.put("conversiontype", "signup"); // type of conversion
customAttributes.put("confirmationref", "54321"); // Transaction ID / Order ID
customAttributes.put("amount", ""); // Transaction amount e.g. 300.5
customAttributes.put("currency", ""); // Transaction currency e.g. USD
// You can track your own custom event attributes!
customAttributes.put("CUSTOM_EVENT_ATTRIBUTE_NAME", "CUSTOM_EVENT_ATTRIBUTE_VALUE");
MPEvent event = new MPEvent.Builder("conversion", MParticle.EventType.Transaction)
.customAttributes(customAttributes)
.build();
if (MParticle.getInstance() != null) {
MParticle.getInstance().logEvent(event);
}
Appendix
The supported custom event types for both Kotlin and Java are:
Navigation
- Track user navigation flows and page transitions within your appLocation
- Record user location-based interactions and movementsSearch
- Capture search queries and search-related user actionsTransaction
- Log financial transactions and purchase-related activitiesUserContent
- Track user-generated content like reviews, comments, or postsUserPreference
- Record user settings, preferences, and customization choicesSocial
- Capture social media interactions and sharing activities
- Kotlin
- Java
val customAttributes = mapOf(
"category" to "Destination Intro",
"title" to "Paris",
)
val event = MPEvent.Builder("Video Watched", EventType.Navigation)
.customAttributes(customAttributes)
.build()
MParticle.getInstance()?.logEvent(event)
Map<String, String> customAttributes = new HashMap<>();
customAttributes.put("category", "Destination Intro");
customAttributes.put("title", "Paris");
MPEvent event = new MPEvent.Builder("Video Watched", EventType.Navigation)
.customAttributes(customAttributes)
.build();
if (MParticle.getInstance() != null) {
MParticle.getInstance().logEvent(event);
}
Track commerce events
Tracking a commerce event requires three steps:
- Defining the product or products that are being purchased
- Creating an object to contain a transaction summary
- Logging the event, including your product definition and transaction summary
- Kotlin
- Java
import com.mparticle.commerce.CommerceEvent
import com.mparticle.commerce.Product
import com.mparticle.commerce.TransactionAttributes
// 1. Create the products
// Create an optional map of custom attributes for the product as key/value pairs of strings
val customAttributes = mutableMapOf<String, String>()
customAttributes["ocean-view"] = "true"
customAttributes["balcony"] = "false"
val product = Product.Builder("Double Room - Econ Rate", "econ-1", 100.00)
.quantity(4.0)
// Include the map of custom attributes created above
.customAttributes(customAttributes)
.build()
// 2. Summarize the transaction
val attributes = TransactionAttributes("foo-transaction-id")
.setRevenue(430.00)
.setTax(30.00)
// 3. Log the purchase event
val event = CommerceEvent.Builder(Product.PURCHASE, product)
.transactionAttributes(attributes)
// Optional custom attributes for the purchase event can be added as a map of key/value string pairs
.customAttributes(mapOf("sale" to "true", "phone-booking" to "true"))
// You can also create a map that is then passed through to the customAttributes builder method. For example:
// val customTransactionAttributes = mutableMapOf<String, String>()
// customTransactionAttributes["sale"] = "true"
// customTransactionAttributes["phone-booking"] = "true"
// .customAttributes(customTransactionAttributes)
.build()
MParticle.getInstance()?.logEvent(event)
import com.mparticle.commerce.CommerceEvent;
import com.mparticle.commerce.Product;
import com.mparticle.commerce.TransactionAttributes;
// 1. Create the products
// Create an optional map of custom attributes for the product as key/value pairs of strings
Map<String, String> productAttributes = new HashMap<>();
productAttributes.put("ocean-view", "true");
productAttributes.put("balcony", "false");
Product product = new Product.Builder("Double Room - Econ Rate", "econ-1", 100.00)
.quantity(4.0)
.customAttributes(productAttributes)
.build();
// 2. Summarize the transaction
TransactionAttributes attributes = new TransactionAttributes("foo-transaction-id")
.setRevenue(430.00)
.setTax(30.00);
Map<String, String> customTransactionAttributes = new HashMap<>();
customTransactionAttributes.put("sale", "true");
customTransactionAttributes.put("phone-booking", "true");
CommerceEvent event = new CommerceEvent.Builder(Product.PURCHASE, product)
.transactionAttributes(attributes)
.customAttributes(customTransactionAttributes)
.build();
if (MParticle.getInstance() != null) {
MParticle.getInstance().logEvent(event);
}