Skip to content
Login Contact

Native Android SDK instrumentation for app analytics

To configure your project, follow these steps:

Add the following repository to your settings.gradle file. Read more about declaring repositories:

maven {
url "https://repositories.mrf.io/nexus/repository/mvn-marfeel-public/"
}

Depending on your application’s use, include one of the following dependencies in your build.gradle within the dependencies section:

  1. If you are using Jetpack Compose
dependencies {
implementationcom.marfeel.compass:compose:1.17.0
}
  1. If you are using XML views:
dependencies {
implementationcom.marfeel.compass:views:1.17.0
}

To begin tracking pages, initialize the SDK using its initialize method and provide your unique Marfeel Account Id as follows:

CompassTracking.initialize(context: Context, /* AccountId */)
We also offer a sample playground application to demonstrate how our SDKs can be used. You can access the GitHub repositories here: Android App

The default value for the Page Technology dimension is set to Android App , represented by the value 4 . However, you can modify this default value using the initialize method, which allows you to specify a different page technology as a parameter.

CompassTracking.initialize(context: Context, accountId: String, pageTechnology: Int)
Custom Page Technologies have IDs above 100 and must be declared at the Organization Settings

All tracking features are made available through a CompassTracking instance:

val tracker = CompassTracking.getInstance()

CompassTracker automatically monitors user time on a page. When a user begins reading a new page, you should provide the page’s canonical URL.

tracker.trackNewPage(url: String)
tracker.trackNewPage(url: String, recirculationSource: String?)

CompassTracker will continue tracking reading time until the trackNewPage method is called again with a different URL or until the developer explicitly invokes the stopTracking() method.

tracker.stopTracking()
tracker.startTracking() has been deprecated in favor of tracker.trackNewPage()

If you want to track a screen instead of a new page, particularly when your view doesn’t have a real URI, you can utilize the trackScreen method. This method accepts a raw name instead of an actual URI for tracking purposes.

tracker.trackScreen(screen: String)
tracker.trackScreen(screen: String, recirculationSource: String?)

If you’re interested in tracking the landing page of the current session, use the following method

tracker.setLandingPage(landingPage: String)

If you want to include UTMs, you’ll need to add them to the landing page.

To track scroll depth, you can provide a view that implements the ScrollingView interface, such as NestedScrollView, ScrollView, or RecyclerView, to both the trackNewPage and trackScreen methods.

tracker.trackNewPage(url: String, scrollView: ScrollingView, recirculationSource: String?)
tracker.trackNewPage(url: String, scrollView: ScrollView, recirculationSource: String?)
tracker.trackNewPage(url: String, scrollView: RecyclerView, recirculationSource: String?)
tracker.trackScreen(screen: String, scrollView: ScrollingView, recirculationSource: String?)
tracker.trackScreen(screen: String, scrollView: ScrollView, recirculationSource: String?)
tracker.trackScreen(screen: String, scrollView: RecyclerView, recirculationSource: String?)

When working with Jetpack Compose, you should use either trackNewPage(url: String) or trackNewScreen(screen: String) along with the composable function:

CompassScrollTrackerEffect(scrollState: ScrollState)

To track a userId instead of the default Marfeel one you can use the method setSiteUserId. ​

setSiteUserId(userId: String)
tracker.setUserId() has been deprecated in favor of tracker.setSiteUserId()

On the other hand, if you need to retrieve marfeel user id for forwarding it to one of our apis, the method you need to use is getUserId()

getUserId(): String

You can specify the type of user with the options below. By default, if not specified, the user will be tracked as Anonymous.

  • ANONYMOUS: for anonymous users
  • LOGGED: for registered users
  • PAID: for subscribers
  • CUSTOM. For custom types you should provide a numeric identifier defined in the Marfeel User Journey UI
// kotlin syntax
tracker.setUserType(UserType.Anonymous)
tracker.setUserType(UserType.Logged)
tracker.setUserType(UserType.Paid)
tracker.setUserType(UserType.Custom(9))
// java syntax
tracker.setUserType(UserType.Anonymous.INSTANCE)
tracker.setUserType(UserType.Logged.INSTANCE)
tracker.setUserType(UserType.Paid.INSTANCE)
tracker.setUserType(new UserType.Custom(9))
TIP:
It's recommended to first provide the user ID and the user journey information before initiating the tracking of the first pageview.

If you want to access the RFV of the user within a session, you can retrieve it using the getRFV method. ​

tracker.getRFV { rfv ->
// The rfv parameter is a JSON string containing the following fields:
// - rfv type:Float -> The combined RFV score
// - r type:Int -> Recency score
// - f type:Int -> Frequecny score
// - v type:Int -> Volume score
}

There’s also a synchronous version of this function available. It should be called from a separate thread. ​

You can track conversions calling the trackConversion(conversion: String) method:

tracker.trackConversion("subscription")

Just like in web, Conversion parameters are available for Native

tracker.trackConversion(
conversion = "{CONVERSION}",
options = ConversionOptions( // optional
id = "{ID}", // each pair {CONVERSION} and {ID} will only be tracked once
value = "{VALUE}",
meta = mapOf("key_1" to "val_1", "key_2" to "val_2"),
scope = ConversionScope.Page // Page | Session | User
)
)

Keep in mind that trackConversion with the same conversion and options.id will only be tracked once

In the following example, if you send the first call:

tracker.trackConversion(
conversion = "conv_1",
options = ConversionOptions(
id = "id_1",
value = "3"
)
)

A second call won’t be tracked because conv_1:id_1 has already been tracked:

tracker.trackConversion(
conversion = "conv_1",
options = ConversionOptions(
id = "id_1",
value = "4"
)
)

In order to mark if the current visit has consent approved or not, sdk offers the following method to use:

tracker.setConsent(true)

User data will be deleted each time the user closes the app if no consent is provided.

tracker.setPageVar("name", "value")
tracker.setSessionVar("name", "value")
tracker.setUserVar("name", "value")

Adds a new persistent user segment

tracker.addUserSegment("segment")

Replaces existing user segments

tracker.setUserSegments(listOf("segment1", "segment2"))

Removes existing user segment

tracker.removeUserSegment("segment")

Clears all user segments

tracker.clearUserSegments()
tracker.setPageMetric("metric", 1)
Only integer values are accepted

All multimedia tracking features are made available through a MultimediaTracking instance:

val multimediaTracker = MultimediaTracking.getInstance()
interface MultimediaTracking {
/**
* Registers multimedia item for tracking
* @param id The item identifier
* @param provider The multimedia provider
* @param providerId The multimedia provider identifier
* @param type The multimedia type
* @param metadata The multimedia metadata
*/
fun initializeItem(id: String, provider: String, providerId: String, type: Type, metadata: MultimediaMetadata)
/**
* Tracks an event for the item matching the provided id.
* @param id The item identifier
* @param event The event to track
* @param eventTime The time when the event has occurred
*/
fun registerEvent(id: String, event: Event, eventTime: Int)
companion object {
/**
*
* @return The singleton instance of the MultimediaTracking interface
*/
fun getInstance(): MultimediaTracking = MultimediaTracker
}
}
enum class Type(val id: String) {
AUDIO("audio"),
VIDEO("video")
}
enum class Event(val id: String) {
PLAY("play"),
PAUSE("pause"),
END("end"),
UPDATE_CURRENT_TIME("updateCurrentTime"),
AD_PLAY("adPlay"),
MUTE("mute"),
UNMUTE("unmute"),
FULL_SCREEN("fullscreen"),
BACK_SCREEN("backscreen"),
ENTER_VIEWPORT("enterViewport"),
LEAVE_VIEWPORT("leaveViewport")
}
data class MultimediaMetadata(
val isLive: Boolean? = false,
val title: String? = null,
val description: String? = null,
val url: String? = null,
val thumbnail: String? = null,
val authors: String? = null,
val publishTime: Long? = null,
val duration: Int? = null
)
Note:
For the full list of available events (Event) and media types (Type), refer to the Multimedia tracking documentation.
multimediaTracker.initializeItem(
"videoId", // mandatory
"youtube", // mandatory
"abcaXala", // mandatory
Type.VIDEO, // mandatory
MultimediaMetadata(
false,
"video-title",
"video-description",
"http://url/to/video",
"http://url/to/thumbnail",
"John, Doe",
1683196435676, // timestamp
125 // time en seconds
)
)
multimediaTracker.registerEvent("videoId", Event.PAUSE, 25)

Track which elements in your app are shown, visible, and clicked. Works for any element you need to measure: recommendation modules, banners, CTAs, or anything else. The SDK reports eligibility, visibility, and clicks; your app decides what those elements are.

val recirculation = Recirculation.getInstance()
Working example: see NewsComposeActivity.kt in the demo app for a complete recirculation tracking flow.

Represents a single trackable element within a module:

PropertyTypeDescription
urlStringCanonical URL of the element’s destination
positionIntZero-based position of the element within the module
data class RecirculationLink(val url: String, val position: Int)

Each module must be tracked through its full lifecycle:

MethodWhen to call
trackEligibleThe module has been selected and will appear in the current page view
trackImpressionOne or more elements become visible on screen
trackClickThe user taps an element within the module
val recirculation = Recirculation.getInstance()
val moduleName = "example-module-name"
val links = listOf(
RecirculationLink(url = "https://example.com/article-1", position = 0),
RecirculationLink(url = "https://example.com/article-2", position = 1),
RecirculationLink(url = "https://example.com/article-3", position = 2)
)
recirculation.trackEligible(moduleName, links)
recirculation.trackImpression(moduleName, listOf(links[0], links[1]))
recirculation.trackImpression(moduleName, links[2])
recirculation.trackClick(moduleName, links[1])
All recirculation methods are fire-and-forget. The SDK dispatches on a background thread and silently ignores failures.

The Experiences API lets you fetch experiences configured in Experience Manager for the current page so your app can render them. You can filter by type or family, resolve remote content on demand, and track user interactions. The SDK returns the configuration; rendering is the app’s responsibility.

All experiences features are made available through an Experiences instance:

val experiences = Experiences.getInstance()
Working example: see MainScreen.kt#L374 in the demo app for a complete experiences fetch and tracking flow.

Fetch experiences for the current targeting using fetchExperiences. The SDK automatically uses the URL from the active page being tracked. This is a suspend function that must be called from a coroutine.

val experiences = Experiences.getInstance()
val result = experiences.fetchExperiences()
fetchExperiences requires the SDK to be initialized via CompassTracking.initialize() and a page to be actively tracked via trackNewPage or trackScreen. If no page is being tracked, an empty list is returned.

Each Experience contains:

PropertyTypeDescription
idStringUnique experience identifier
nameStringExperience name from the server configuration
typeExperienceTypeExperience type (INLINE, FLOWCARDS, COMPASS, AD_MANAGER, etc.)
familyExperienceFamily?Optional experience family (RECOMMENDER, PAYWALL, WIDGET, etc.). Null when not specified by the server
placementString?Placement identifier
contentUrlString?URL to fetch the experience content from
contentTypeExperienceContentTypeContent type (TEXT_HTML, JSON, AMP, etc.)
featuresMap<String, Any>?Arbitrary feature flags and configuration
strategyString?Placement strategy (e.g., replace, append)
resolvedContentString?The fetched content body, populated after calling resolve() or when resolve = true
rawJsonMap<String, Any>The full original JSON for accessing fields not explicitly modeled

You can filter experiences by type, family, or both:

val experiences = Experiences.getInstance()
// Filter by type
val inlineOnly = experiences.fetchExperiences(
filterByType = ExperienceType.INLINE
)
// Filter by family
val recommenders = experiences.fetchExperiences(
filterByFamily = ExperienceFamily.RECOMMENDER
)
// Combine both filters (AND logic)
val inlineRecommenders = experiences.fetchExperiences(
filterByType = ExperienceType.INLINE,
filterByFamily = ExperienceFamily.RECOMMENDER
)

Available experience families:

Enum ValueServer Key
TWITTERtwitterexperience
FACEBOOKfacebookexperience
YOUTUBEyoutubeexperience
RECOMMENDERrecommenderexperience
TELEGRAMtelegramexperience
GATHERINGgatheringexperience
AFFILIATEaffiliateexperience
PODCASTpodcastexperience
EXPERIMENTATIONexperimentsexperience
WIDGETwidgetexperience
MARFEEL_PASSpassexperience
SCRIPTscriptexperience
PAYWALLpaywallexperience
MARFEEL_SOCIALmarfeelsocial
The Server Key is the raw string value returned by the server in the family field. Use it when accessing rawJson directly or when debugging API responses. When the server returns an unrecognized value, it maps to ExperienceFamily.UNKNOWN. When the field is absent, it is null.

By default, fetchExperiences does not resolve content. You can enable automatic resolution for all experiences that have a contentUrl, or resolve individually on demand:

val experiences = Experiences.getInstance()
// No content resolution (default)
val result = experiences.fetchExperiences()
result.first().resolvedContent // null
// Resolve all content automatically
val result = experiences.fetchExperiences(resolve = true)
result.first().resolvedContent // contains the fetched content
// Resolve individually on demand
val result = experiences.fetchExperiences()
result.first().resolve() // suspend function

Add custom targeting key-value pairs that will be sent with every experiences request:

experiences.addTargeting("key", "value")

Each experience that your app consumes must be tracked through its full lifecycle. Call the appropriate method as each stage occurs. Tracking link interactions uses RecirculationLink, defined in the Recirculation Tracking section above.

MethodWhen to call
trackEligibleThe experience has been selected and is intended to be shown on the current page view
trackImpressionThe experience content has been rendered and is visible to the user
trackClickThe user tapped on a specific link within the experience
trackCloseThe user dismissed or closed the experience
val experiences = Experiences.getInstance()
val result = experiences.fetchExperiences(filterByFamily = ExperienceFamily.RECOMMENDER)
val recommender = result.first()
val links = listOf(
RecirculationLink(url = "https://example.com/article-1", position = 0),
RecirculationLink(url = "https://example.com/article-2", position = 1),
RecirculationLink(url = "https://example.com/article-3", position = 2)
)
// The experience will be used in this page view
experiences.trackEligible(recommender, links)
// First two links are visible on screen
experiences.trackImpression(recommender, listOf(links[0], links[1]))
// After scrolling, the third link becomes visible
experiences.trackImpression(recommender, links[2])
// The user tapped a link inside the experience
experiences.trackClick(recommender, links[1])
// The user dismissed the experience
experiences.trackClose(recommender)