← Metriku

Documentation

Kotlin. App Key → Android SDK → optional Firebase FCM → push, live config, and the console. Android SDK v1.7.1 · Releases.

How are you integrating?

AI copy-paste prompts

Paste into Cursor / Claude / ChatGPT. Every prompt installs io.github.haxhiuurim:metriku-android:1.7.1 from Maven Central (mavenCentral(), no GitHub PAT). Prefer Project setup → Setup Android → I’m implementing with AI for your real App Key + package.

A · Full Android integration (recommended)

Integrate Metriku analytics + messaging into this Android (Kotlin) app end-to-end.

## Install from Maven Central (required preferred path)
Public artifact — no GitHub PAT, no private Packages login, no DNS setup for consumers.

Coordinate: io.github.haxhiuurim:metriku-android:1.7.1
Repository: mavenCentral() only (https://repo1.maven.org/maven2)
Kotlin import: import dev.metriku.sdk.Metriku   ← package name ≠ Maven groupId

Steps:
1. Open settings.gradle.kts (or settings.gradle). Under dependencyResolutionManagement.repositories, ensure mavenCentral() is present.
2. Open the app module build.gradle.kts (or build.gradle). Add:
   implementation("io.github.haxhiuurim:metriku-android:1.7.1")
   Or pin via gradle/libs.versions.toml and implementation(libs.metriku.android).
3. Sync Gradle. Confirm the dependency resolves (no 401 / “Could not find”).
4. Call Metriku.initialize(applicationContext, APP_KEY) — host is always https://metriku.dev.

Do NOT:
- Check in metriku-release.aar or use implementation(files("libs/…")) unless Maven Central cannot resolve
- Add maven { url = uri("https://maven.pkg.github.com/…") } or gpr.user / gpr.key credentials
- Change the Maven groupId or invent a different artifact name

Fallback only if Central is unreachable: download metriku-release.aar from
https://github.com/haxhiuurim/AndroidMetrikuSDK/releases/tag/1.7.1 → app/libs/
then implementation(files("libs/metriku-release.aar")).

```kotlin
// 1) settings.gradle.kts — dependencyResolutionManagement.repositories { … }
mavenCentral()
// Do NOT add a GitHub Packages maven { } block or ask for a PAT.

// 2) app/build.gradle.kts — dependencies { … }
implementation("io.github.haxhiuurim:metriku-android:1.7.1")

// Optional — version catalog (gradle/libs.versions.toml):
// metrikuAndroid = "1.7.1"
// metriku-android = { group = "io.github.haxhiuurim", name = "metriku-android", version.ref = "metrikuAndroid" }
// then: implementation(libs.metriku.android)

// 3) Sync Gradle (Android Studio: elephant icon / File → Sync Project with Gradle Files)

// 4) Import stays the Kotlin package (not the Maven groupId):
// import dev.metriku.sdk.Metriku
```

Docs: https://metriku.dev/docs/android#sdk
Console: https://metriku.dev/dashboard

## Credentials (fill these)
- App Key: YOUR_APP_KEY
- Android package / applicationId: com.company.app  (must match Gradle + Metriku project Android package)
- API host is FIXED: https://metriku.dev  (do NOT add a custom base URL)

## Bootstrap (after Maven Central dependency resolves)
1. Confirm io.github.haxhiuurim:metriku-android:1.7.1 is on the app classpath from mavenCentral()
2. In Application.onCreate (or first Activity):
   Metriku.initialize(applicationContext, "YOUR_APP_KEY")
3. Debug builds only: Metriku.setSandbox(true)
4. Metriku.Notifications.requestPermission(activity) { granted -> }
5. Register Activity for IAM: Metriku.InAppMessages.registerActivity(this) in onResume; clear in onPause if needed
6. Handle notification taps: Metriku.Notifications.handleNotificationIntent(intent) in onCreate/onNewIntent
7. Optional FCM: when you receive a token, Metriku.Notifications.setPushToken(token)
8. Metriku.User.printDebugIdentity()

## Default attributes (ALWAYS add after initialize)
Metriku.User.setAttributes(mapOf(
  "app_version" to BuildConfig.VERSION_NAME,
  "platform" to "android",
  "device_model" to android.os.Build.MODEL,
  "os_version" to android.os.Build.VERSION.RELEASE,
))

## Identity
- If the app uses RevenueCat (SDK ≥ 1.7.1 preferred):
  Metriku.revenueCatIdentitySync = { id ->
    if (id != null) Purchases.sharedInstance.logIn(id) { _, _ -> }
    else Purchases.sharedInstance.logOut { _, _ -> }
  }
  Then Metriku.login(sameStringAsRevenueCat.appUserID) after auth (MUST match RC app_user_id).
  Or call Metriku.login(Purchases.sharedInstance.appUserID) after Purchases.logIn if you skip the hook.
- Metriku.logout() on sign-out
- Tags: Metriku.User.addTag / addTags / removeTag / removeTags / getTags
- Attributes: Metriku.User.setAttribute / setAttributes / getAttributes
- Metriku.User.deviceId(), Metriku.User.setLanguage(code)
- Consent: Metriku.setConsentRequired / setConsentGiven
- GDPR: Metriku.requestDataDeletion()

## Analytics — instrument the WHOLE app (required)
1) SCREENS: Metriku.Analytics.screen("ScreenName") on every screen appear
2) BUTTONS / CTAs: Metriku.Analytics.trackButton("button_id", screen = "ScreenName")
3) PRODUCT EVENTS: Metriku.Analytics.track("event_name", mapOf(...))
4) Optional Metriku.Analytics.flush() — usually unnecessary (auto debounce)

## Product flows — OPTIONAL (multi-step journeys, non-revenue)
Use Metriku.Flow when you want step-by-step conversion (start → steps → complete/quit).
Appears under Dashboard → Flows (not subscription Funnels).
Pass optional value when the user picks a choice on a step. Dashboard → Flows renders those choices as branch nodes in the step funnel (same visual model as the sales Funnel). Steps without values stay a single spine. Flow details still list per-step value breakdowns.
Screen appear → step("screen_name") with no value. Button / exclusive choice on that screen → same step name + value (e.g. cancel, keep_premium, dismiss). New screen after a choice → new step name; choices again via value. Abandon → quit(at: current step); success → complete.
Example (branching cancel / manage subscription):
  Metriku.Flow.start("manage_subscription")
  Metriku.Flow.step("manage_subscription", "access_active")
  // Choice on this screen → branch in Flows funnel:
  Metriku.Flow.step("manage_subscription", "access_active", value = "cancel")
  // or value = "keep_premium" / "dismiss"
  Metriku.Flow.step("manage_subscription", "cancel_reasons")
  Metriku.Flow.step("manage_subscription", "cancel_reasons", value = "too_expensive")
  Metriku.Flow.step("manage_subscription", "winback")
  Metriku.Flow.step("manage_subscription", "winback", value = "try_offer")
  Metriku.Flow.complete("manage_subscription")
  // or Metriku.Flow.quit("manage_subscription", at = "access_active", value = "dismiss")
Skip this section if the app has no multi-step product journeys to measure.

## Subscription funnel — pick ONE path (never both)
A) App HAS RevenueCat (+ Metriku webhook configured) — APP CALLS:
  1. Install Metriku.revenueCatIdentitySync (SDK ≥ 1.7.1) so login/logout keep RC appUserID in sync
  2. Metriku.login(sameStringAsRevenueCat.appUserID)
  3. Metriku.Analytics.trackPaywallView() when the paywall UI is shown
  DO NOT call trackTrialStarted / trackTrialConverted / trackPurchaseCompleted /
    trackRenewed / trackCanceled / trackBillingGraceFailed
  Webhook URL: Metriku → App Settings → RevenueCat webhooks → Copy URL
  Auth in RevenueCat MUST include BOTH:
    1) Authorization header = Bearer token from Metriku (Generate & save)
    2) HMAC signing secret from RevenueCat pasted into Metriku
B) App does NOT use RevenueCat:
  - trackPaywallView + trackTrialStarted + trackTrialConverted (or trackPurchaseCompleted)
    + trackRenewed + trackCanceled + trackBillingGraceFailed at real moments

## Live config / experiments
- Metriku.Config.whenReady { … }
- Metriku.Config.getBool / getString / getDouble / getInt / getJSON / getArray /
  getStringArray / getObjectArray / getValue / allKeys
- Metriku.Config.refresh(force = true) / stopPolling()
- Metriku.Experiments.variant("exp_id") / Metriku.Experiments.all()

## In-app messages
- Metriku.InAppMessages.registerActivity(activity)
- Metriku.InAppMessages.fetchAndMaybePresent()

## Push (optional — only if you need push / in-app delivery from Metriku server)
- Add Firebase Android app with package com.company.app; put google-services.json in the app module
- Upload Firebase service-account JSON to Metriku Settings (NOT google-services.json for the server)
- Do NOT set up Apple APNs .p8 keys — those are iOS-only
- REQUIRED: create a FirebaseMessagingService that (1) forwards the FCM token and
  (2) DISPLAYS the notification when received (foreground / data delivery will NOT show
  a tray notification unless you post one). Android allows only one MESSAGING_EVENT service.

```kotlin
// app/src/main/java/.../MyFirebaseMessagingService.kt
package com.company.app

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import dev.metriku.sdk.Metriku

class MyFirebaseMessagingService : FirebaseMessagingService() {
  override fun onNewToken(token: String) {
    Metriku.Notifications.setPushToken(token)
  }

  override fun onMessageReceived(message: RemoteMessage) {
    // REQUIRED — post a system notification so the user sees Metriku pushes
    // (especially when the app is in the foreground).
    val title = message.notification?.title
      ?: message.data["title"]
      ?: "Notification"
    val body = message.notification?.body
      ?: message.data["body"]
      ?: ""
    val channelId = "metriku_push"
    val nm = getSystemService(NotificationManager::class.java)
    if (Build.VERSION.SDK_INT >= 26) {
      nm.createNotificationChannel(
        NotificationChannel(channelId, "Push", NotificationManager.IMPORTANCE_DEFAULT)
      )
    }
    val launch = packageManager.getLaunchIntentForPackage(packageName)
      ?: Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
    // Forward Metriku data keys so handleNotificationIntent can open deep links.
    for ((k, v) in message.data) launch.putExtra(k, v)
    val pi = PendingIntent.getActivity(
      this, 0, launch,
      PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )
    val notif = NotificationCompat.Builder(this, channelId)
      .setSmallIcon(applicationInfo.icon)
      .setContentTitle(title)
      .setContentText(body)
      .setAutoCancel(true)
      .setContentIntent(pi)
      .build()
    nm.notify((message.messageId ?: System.currentTimeMillis().toString()).hashCode(), notif)
  }
}
```

AndroidManifest.xml (inside <application>):
```xml
<service
  android:name=".MyFirebaseMessagingService"
  android:exported="false">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
  </intent-filter>
</service>
```

Also in Activity onCreate / onNewIntent:
  Metriku.Notifications.handleNotificationIntent(intent)

If the host app already has an FCM service, do NOT add a second one — call
Metriku.Notifications.setPushToken(token) from onNewToken AND display the notification
from onMessageReceived in that existing service.
The SDK also ships MetrikuFirebaseMessagingService as a token/tracking fallback only —
it does not replace your responsibility to show the tray notification.

## Done checklist
1. applicationId is com.company.app
2. App Key YOUR_APP_KEY in Metriku.initialize
3. All screens/buttons/events instrumented; platform=android attributes set
4. If push: FirebaseMessagingService created with setPushToken + display notification in onMessageReceived
5. If RevenueCat: only login + trackPaywallView (webhook auth in Metriku console)
6. Run on a physical Android device → confirm Metriku Users / Analytics update

Do NOT invent API hosts, do NOT upload APNs .p8 for Android, and do NOT skip the package name match.

AFTER this prompt: return to Metriku → Project setup → Setup Android for optional Firebase
(service account JSON) and RevenueCat webhook (Bearer + HMAC) if you need push, in-app, or subscription data.

B · Push only

Wire Metriku push on this Android (Kotlin) target.
Install SDK from Maven Central first (no PAT):
  repositories { mavenCentral() }
  implementation("io.github.haxhiuurim:metriku-android:1.7.1")
  import dev.metriku.sdk.Metriku
After Metriku.initialize(context, APP_KEY):
  Metriku.Notifications.requestPermission(activity) { granted -> }
  Metriku.Notifications.handleNotificationIntent(intent)
REQUIRED — create FirebaseMessagingService (or extend existing):
  1) onNewToken → Metriku.Notifications.setPushToken(token)
  2) onMessageReceived → post a NotificationCompat notification (create channel on API 26+).
     Foreground / data delivery will NOT show a tray item unless you display it.
  3) PendingIntent extras should include FCM data keys; Activity calls
     Metriku.Notifications.handleNotificationIntent(intent)
Declare the service in AndroidManifest with com.google.firebase.MESSAGING_EVENT.
Only ONE MessagingService may handle MESSAGING_EVENT — never register two.
Log.d("Metriku", Metriku.User.deviceId())
Docs: https://metriku.dev/docs/android#push
Add Firebase Android app + google-services.json, then upload Firebase service-account JSON to Metriku Settings.
Do NOT configure Apple APNs .p8 (iOS only).
Test from Metriku → Messages using the printed deviceId.

C · Funnel + RevenueCat (recommended)

Instrument Metriku WITH RevenueCat on Android (Kotlin).
Install from Maven Central: mavenCentral() + implementation("io.github.haxhiuurim:metriku-android:1.7.1")
Import: import dev.metriku.sdk.Metriku
Initialize with App Key only (host https://metriku.dev).

DEFAULT ATTRIBUTES (always):
  app_version, platform=android, device_model, os_version
  Metriku.User.setAttributes(mapOf(...))

FULL PRODUCT ANALYTICS (required — not just paywall):
  - Metriku.Analytics.screen on every screen
  - Metriku.Analytics.trackButton on meaningful taps
  - Metriku.Analytics.track for feature/product events

SUBSCRIPTIONS — ONLY THESE TWO APP CALLS when RC webhook is configured:
1) Metriku.login(sameUserIdAsRevenueCat) after auth / Purchases.logIn
2) Metriku.Analytics.trackPaywallView() when the paywall is shown
DO NOT call trackTrial* / trackPurchase* / trackRenewed / trackCanceled / billing grace helpers.

WEBHOOK: Metriku Settings → copy URL → RC; configure BOTH:
  1) Bearer Authorization = Generate&save in Metriku → paste into RC Authorization field
  2) HMAC secret = enable in RC → paste into Metriku HMAC field
Verify Webhook log + Conversation funnel.

Docs: https://metriku.dev/docs/android#funnel https://metriku.dev/docs/android#revenuecat

D · Funnel without RevenueCat

This Android app does NOT use RevenueCat. Fill the Metriku Conversation funnel from the SDK.
Install from Maven Central: mavenCentral() + implementation("io.github.haxhiuurim:metriku-android:1.7.1")
Import: import dev.metriku.sdk.Metriku
Initialize with App Key only (host https://metriku.dev).

Call at the matching product moments:
  Metriku.Analytics.trackPaywallView()
  Metriku.Analytics.trackTrialStarted()
  Metriku.Analytics.trackTrialConverted()        // after trial → paid
  // OR Metriku.Analytics.trackPurchaseCompleted() // paid with no trial
  Metriku.Analytics.trackRenewed()
  Metriku.Analytics.trackCanceled()
  Metriku.Analytics.trackBillingGraceFailed()    // if you have a grace UX

Do NOT connect a RevenueCat webhook for the same events (or you will double-count).
Custom events: Metriku.Analytics.track("feature_x_used", mapOf(...))
Docs: https://metriku.dev/docs/android#funnel