Kotlin Multiplatform web analytics installation

  1. Install the dependency

    Required

    Add the PostHog KMP SDK to your shared module's commonMain source set:

    shared/build.gradle.kts
    kotlin {
    sourceSets {
    commonMain.dependencies {
    implementation("com.posthog:posthog-kmp:0.+")
    }
    }
    }

    0.+ resolves to the latest 0.x release. The SDK is a pre-release, so the API can change between minor versions – pin an exact version from Maven Central if you would rather upgrade deliberately. Kotlin/Wasm support requires 0.2.0 or higher.

  2. Configure PostHog

    Required

    Call PostHog.setup() once, early in your app's lifecycle. The config is shared across every target – only the PostHogContext differs per platform.

    Android needs the Application instance, so set PostHog up from your Application class – not from an Activity, whose onCreate re-runs on every recreation (for example, on rotation):

    MyApplication.kt
    import android.app.Application
    import com.posthog.kmp.PostHog
    import com.posthog.kmp.PostHogConfig
    import com.posthog.kmp.PostHogContext
    class MyApplication : Application() {
    override fun onCreate() {
    super.onCreate()
    PostHog.setup(
    config = PostHogConfig(
    apiKey = "<ph_project_token>",
    host = "https://us.i.posthog.com",
    ),
    context = PostHogContext(this),
    )
    }
    }

    Register the class in your AndroidManifest.xml:

    android/src/main/AndroidManifest.xml
    <application android:name=".MyApplication" ...>
  3. Track screen views

    Recommended

    Despite the name, the web analytics dashboard can be used to track screen views in mobile apps, too. Open your app and view some screens to generate some events.

    Screen views are off by default. Set captureScreenViews = true to capture them automatically – screen views on Android and iOS, pageviews on the web:

    Kotlin
    PostHogConfig(
    apiKey = "<ph_project_token>",
    host = "https://us.i.posthog.com",
    captureScreenViews = true,
    )

    You can also capture a screen view yourself from shared code:

    Kotlin
    import com.posthog.kmp.PostHog
    PostHog.screen(
    screenName = "Dashboard",
    properties = mapOf(
    "background" to "blue"
    )
    )
  4. Next steps

    Recommended

    After installing PostHog and ensuring autocapture is enabled, head to your web analytics dashboard to see your data. And then check out our start here guide.

    PostHog tip: Web analytics works with anonymous events. This means if you are primarily using PostHog for web analytics, it can be significantly cheaper for you.

Still have questions?

Was this page useful?