Android SDK
Overview
The MetaRouter Android SDK enables you to capture analytics events from your Kotlin-based Android application and route them through your MetaRouter infrastructure. It leverages the open-source, MIT-licensed Segment Analytics Kotlin SDK to handle event collection and delivery.
Rather than maintaining a separate implementation, MetaRouter uses Segment’s Android SDK to efficiently queue, batch, and asynchronously send enriched events to your configured MetaRouter cluster. Once received, MetaRouter forwards the data to your downstream integrations based on your pipeline configuration.
The SDK is designed to be non-blocking and performant, ensuring minimal impact on your app’s responsiveness.
Installation Instructions
Install the Segment Analytics Android SDK
Follow the official instructions here to install the latest version of the analytics-kotlin library:
https://segment.com/docs/connections/sources/catalog/libraries/mobile/kotlin-android/
At the time of writing, the latest supported version is 1.19.2.
2. Create AnalyticsManager
The Segment Analytics Kotlin SDK requires you to manage your own singleton instance of the Analytics
client. We recommend using a Kotlin object
to manage this shared instance across your application.
import android.content.Context
import com.segment.analytics.kotlin.android.Analytics
import com.segment.analytics.kotlin.core.Analytics
object AnalyticsManager {
@Volatile
private var analytics: Analytics? = null
fun initialize(context: Context) {
if (analytics == null) {
synchronized(this) {
if (analytics == null) {
analytics = Analytics("{{METAROUTER_WRITE_KEY}}", context.applicationContext) {
apiHost = "{{METAROUTER_INGESTION_ENDPOINT}}"
}
}
}
}
}
fun get(): Analytics {
return analytics
?: throw IllegalStateException("AnalyticsManager must be initialized before use. Call initialize(context) in your Application class.")
}
}
Replace the placeholders with values from your MetaRouter configuration:
{{METAROUTER_WRITE_KEY}}
– The write key for your MetaRouter pipeline. This must be a string.{{METAROUTER_INGESTION_ENDPOINT}}
– The MetaRouter event ingestion endpoint (e.g.,demo-prod.mr-in.com/v1
). Do not include the protocol (https://
), but be sure to include the/v1
path suffix.
You can find additional configuration options in Segment’s Android (Kotlin) documentation .
During initialization, you may see a failed request to
cdn-settings.segment.com
. This is expected—Segment attempts to fetch remote settings by default. These settings are optional and do not affect the SDK’s ability to send data to MetaRouter.
Call Identify, Track, Screen and Group Events
You can now use the standard methods provided by the Segment Analytics Kotlin SDK to send data to your MetaRouter instance. The MetaRouter integration supports all core event types from the SDK, including identify
, track
, screen
, and group
.
Refer to Segment’s documentation for full method usage.
val analytics = AnalyticsManager.get()
// Identify a known user
analytics.identify("[email protected]") {
traits["name"] = "John Doe"
traits["plan"] = "Premium"
}
// Track a custom event
analytics.track("Submit Button Clicked") {
properties["formId"] = "signup_form"
properties["success"] = true
}
// Track a screen view
analytics.screen("Checkout Screen") {
properties["step"] = 2
properties["paymentMethod"] = "Google Pay"
}
// Associate a user with a group (e.g., organization or team)
analytics.group("org_456") {
traits["name"] = "Acme Inc."
traits["industry"] = "SaaS"
}
These methods can be called from anywhere in your app once AnalyticsManager.initialize(context)
has been called during application startup (typically in your Application
class).
Troubleshooting & FAQ
Does the SDK perform any work on the UI thread?
No. In our testing, we used Android’s StrictMode to force the app to crash on any disk, network, or other long-running operations on the UI thread:
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyDeath() // Crash app on violation (for dev only)
.build()
)
The SDK passed without issue. All event handling is performed asynchronously and should not block or degrade your app’s UI responsiveness.
Will enabling recordScreenViews interfere with manual screen tracking?
No. Setting recordScreenViews
to true
simply automates the process of tracking screen views using Android’s built-in activity lifecycle. It does not override or block manual screen()
calls. If you prefer full control over screen tracking, you can leave this option disabled and use the screen()
method directly.
What is the maximum length allowed for userId in an identify() call?
The SDK does not enforce a strict character limit for userId
, but we recommend keeping it under 255 characters as a best practice to ensure compatibility with most downstream systems.
How can I persist user traits across all events?
The SDK automatically includes the userId in all events after an identify()
call- but it does not persist traits across future events like track()
. Traits are only included in the identify()
payload.
For example:
analytics.identify("user-123", buildJsonObject {
put("username", "MisterWhiskers")
put("email", "[email protected]")
put("plan", "premium")
})
analytics.track("Submit Button Clicked")
The identify payload sent to MetaRouter will include the full set of traits:
{
"type": "identify",
"userId": "user-123",
"traits": {
"username": "MisterWhiskers",
"email": "[email protected]",
"plan": "premium"
},
...
}
But the track event will only include the userId:
{
"type": "track",
"userId": "user-123",
"event": "Submit Button Clicked",
...
}
If you want traits included in future events, you will need to either:
- Store and manually re-attach them using custom context/traits logic, or
- Handle enrichment downstream in your pipeline or customer data platform.
Do I need to pass userId every time I call identify()?
Yes. The userId is required in each identify() call. If you want to update traits for a user, you must pass the userId again—even if it hasn’t changed.
Updated 6 days ago