Native Android SDK instrumentation for app analytics
Installation
Section titled “Installation”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:
- If you are using Jetpack Compose
dependencies { implementation ‘com.marfeel.compass:compose:1.17.0’}- If you are using XML views:
dependencies { implementation ‘com.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 */)Page Technology
Section titled “Page Technology”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)All tracking features are made available through a CompassTracking instance:
val tracker = CompassTracking.getInstance()Page Tracking
Section titled “Page Tracking”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?)Landing Page Tracking
Section titled “Landing Page Tracking”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.
Scroll Tracking
Section titled “Scroll Tracking”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)User Identification
Section titled “User Identification”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(): StringUser Journey
Section titled “User Journey”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 syntaxtracker.setUserType(UserType.Anonymous)tracker.setUserType(UserType.Logged)tracker.setUserType(UserType.Paid)tracker.setUserType(UserType.Custom(9))// java syntaxtracker.setUserType(UserType.Anonymous.INSTANCE)tracker.setUserType(UserType.Logged.INSTANCE)tracker.setUserType(UserType.Paid.INSTANCE)tracker.setUserType(new UserType.Custom(9))It's recommended to first provide the user ID and the user journey information before initiating the tracking of the first pageview.
User RFV
Section titled “User RFV”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.
Conversions tracking
Section titled “Conversions tracking”You can track conversions calling the trackConversion(conversion: String) method:
tracker.trackConversion("subscription")Conversion parameters
Section titled “Conversion parameters”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" ) )Consent tracking
Section titled “Consent tracking”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.
Custom Dimensions
Section titled “Custom Dimensions”Page vars
Section titled “Page vars”tracker.setPageVar("name", "value")Session vars
Section titled “Session vars”tracker.setSessionVar("name", "value")User vars
Section titled “User vars”tracker.setUserVar("name", "value")User segments
Section titled “User segments”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()Custom Metrics
Section titled “Custom Metrics”Page metrics
Section titled “Page metrics”tracker.setPageMetric("metric", 1)Multimedia tracking
Section titled “Multimedia tracking”All multimedia tracking features are made available through a MultimediaTracking instance:
val multimediaTracker = MultimediaTracking.getInstance()Exposed interfaces
Section titled “Exposed interfaces”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)For the full list of available events (
Event) and media types (Type), refer to the Multimedia tracking documentation.
To initialize a new media
Section titled “To initialize a new media”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 ))To track a new event
Section titled “To track a new event”multimediaTracker.registerEvent("videoId", Event.PAUSE, 25)Recirculation Tracking
Section titled “Recirculation Tracking”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()NewsComposeActivity.kt in the demo app for a complete
recirculation tracking flow.
RecirculationLink
Section titled “RecirculationLink”Represents a single trackable element within a module:
| Property | Type | Description |
|---|---|---|
url | String | Canonical URL of the element’s destination |
position | Int | Zero-based position of the element within the module |
data class RecirculationLink(val url: String, val position: Int)Tracking lifecycle
Section titled “Tracking lifecycle”Each module must be tracked through its full lifecycle:
| Method | When to call |
|---|---|
trackEligible | The module has been selected and will appear in the current page view |
trackImpression | One or more elements become visible on screen |
trackClick | The 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])Experiences
Section titled “Experiences”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()MainScreen.kt#L374 in the demo app for a
complete experiences fetch and tracking flow.
Fetching Experiences
Section titled “Fetching Experiences”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:
| Property | Type | Description |
|---|---|---|
id | String | Unique experience identifier |
name | String | Experience name from the server configuration |
type | ExperienceType | Experience type (INLINE, FLOWCARDS, COMPASS, AD_MANAGER, etc.) |
family | ExperienceFamily? | Optional experience family (RECOMMENDER, PAYWALL, WIDGET, etc.). Null when not specified by the server |
placement | String? | Placement identifier |
contentUrl | String? | URL to fetch the experience content from |
contentType | ExperienceContentType | Content type (TEXT_HTML, JSON, AMP, etc.) |
features | Map<String, Any>? | Arbitrary feature flags and configuration |
strategy | String? | Placement strategy (e.g., replace, append) |
resolvedContent | String? | The fetched content body, populated after calling resolve() or when resolve = true |
rawJson | Map<String, Any> | The full original JSON for accessing fields not explicitly modeled |
Filtering
Section titled “Filtering”You can filter experiences by type, family, or both:
val experiences = Experiences.getInstance()
// Filter by typeval inlineOnly = experiences.fetchExperiences( filterByType = ExperienceType.INLINE)
// Filter by familyval 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 Value | Server Key |
|---|---|
TWITTER | twitterexperience |
FACEBOOK | facebookexperience |
YOUTUBE | youtubeexperience |
RECOMMENDER | recommenderexperience |
TELEGRAM | telegramexperience |
GATHERING | gatheringexperience |
AFFILIATE | affiliateexperience |
PODCAST | podcastexperience |
EXPERIMENTATION | experimentsexperience |
WIDGET | widgetexperience |
MARFEEL_PASS | passexperience |
SCRIPT | scriptexperience |
PAYWALL | paywallexperience |
MARFEEL_SOCIAL | marfeelsocial |
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.
Content Resolution
Section titled “Content Resolution”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 automaticallyval result = experiences.fetchExperiences(resolve = true)result.first().resolvedContent // contains the fetched content
// Resolve individually on demandval result = experiences.fetchExperiences()result.first().resolve() // suspend functionCustom Targeting
Section titled “Custom Targeting”Add custom targeting key-value pairs that will be sent with every experiences request:
experiences.addTargeting("key", "value")Tracking
Section titled “Tracking”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.
| Method | When to call |
|---|---|
trackEligible | The experience has been selected and is intended to be shown on the current page view |
trackImpression | The experience content has been rendered and is visible to the user |
trackClick | The user tapped on a specific link within the experience |
trackClose | The 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 viewexperiences.trackEligible(recommender, links)
// First two links are visible on screenexperiences.trackImpression(recommender, listOf(links[0], links[1]))
// After scrolling, the third link becomes visibleexperiences.trackImpression(recommender, links[2])
// The user tapped a link inside the experienceexperiences.trackClick(recommender, links[1])
// The user dismissed the experienceexperiences.trackClose(recommender)