AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-product-analytics

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-product-analytics at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 62

references/android.md · 24000

PostHog.group( type = "company", key = "company_id_in_your_db" )


-   Associate the events for this session with a group AND update the properties of that group

```kotlin
import com.posthog.PostHog

PostHog.group(
    type = "company",
    key = "company_id_in_your_db",
    groupProperties = mapOf("name" to "Awesome Inc.")
)

The name is a special property which is used in the PostHog UI for the name of the group. If you don't specify a name property, the group ID will be used instead.

Error tracking

To set up error tracking in your project, see the error tracking docs.

Logs

To set up logs in your Android app, follow the Android logs installation guide. The SDK exposes PostHog.logger.{trace,debug,info,warn,error,fatal} for sending structured records to PostHog Logs, with batching, offline persistence, and a rate cap built in.

Minimum version: com.posthog:[email protected] or later.

Session replay

To set up session replay in your project, all you need to do is install the Android SDK, enable "Record user sessions" in your project settings and enable the sessionReplay option.

Surveys

To set up surveys, follow the additional installation instructions for Android. Surveys launched with popover presentation are automatically shown to users matching the display conditions you set up.

Offline behavior

The PostHog Android SDK will continue to capture events when the device is offline. The events are stored in a queue in the device's file storage and are flushed when the device is online.

  • The queue has a maximum size defined by maxQueueSize in the configuration.
  • When the queue is full, the oldest event is deleted first.
  • The queue is flushed when the app is restarted and the device is online.
  • When you call flush() while the device is offline, it aborts early and the events are not flushed.

Debug mode

If you're not seeing the expected events being captured, the feature flags being evaluated, surveys being shown, or session replay/error tracking behavior, you can enable debug mode to see what's happening.

You can enable debug mode by setting the debug option to true in the PostHogAndroidConfig object. This will enable verbose logs about the inner workings of the SDK.

val config = PostHogAndroidConfig(apiKey = POSTHOG_API_KEY, host = POSTHOG_HOST).apply {
    debug = true
    // ... other config options
}

All configuration options

When creating the PostHog client, pass a PostHogAndroidConfig. It inherits the core PostHogConfig options and adds Android-specific options.

import com.posthog.PersonProfiles
import com.posthog.android.PostHogAndroidConfig

val config = PostHogAndroidConfig(
    apiKey = POSTHOG_API_KEY,
    host = POSTHOG_HOST
).apply {
    captureApplicationLifecycleEvents = true
    captureScreenViews = true
    captureDeepLinks = true

    flushAt = 20
    maxQueueSize = 1000
    maxBatchSize = 50
    maxRetries = 3
    flushIntervalSeconds = 30

    debug = false
    optOut = false

    sendFeatureFlagEvent = true
    featureFlagCalledCacheSize = 1000
    preloadFeatureFlags = true
    evaluationContexts = listOf("production", "android", "mobile")

    setDefaultPersonProperties = true
    personProfiles = PersonProfiles.IDENTIFIED_ONLY
    reuseAnonymousId = false

    sessionReplay = false
    errorTrackingConfig.autoCapture = false
}

Android-specific options

| Option | Default | Description | | --- | --- | --- | | captureApplicationLifecycleEvents | true | Captures Application Installed, Application Updated, Application Opened, and Application Backgrounded. | | captureScreenViews | true | Captures $screen for foreground android.app.Activity screens. | | captureDeepLinks | true | Captures Deep Link Opened with URL/query/referrer properties. |

Core options

| Option | Default | Description | | --- | --- | --- | | debug | false | Enables verbose SDK logs in Logcat. You can also call PostHog.debug(true). | | optOut | false | Prevents data capture when enabled. You can also call PostHog.optOut() and PostHog.optIn(). | | flushAt | 20 | Number of queued events that triggers a flush. | | maxQueueSize | 1000 | Maximum number of events kept across memory and disk before FIFO eviction. | | maxBatchSize | 50 | Maximum number of events sent in one batch request. | | maxRetries | 3 | Maximum retry attempts for push-subscription registration failures. It does not apply to event, session recording, or log ingestion. | | flushIntervalSeconds | 30 | Maximum delay before queued data is flushed. | | encryption | null | Optional PostHogEncryption implementation for encrypting persisted queued events. | | proxy | null | Optional java.net.Proxy for PostHog API requests. | | getAnonymousId | generated UUID | Optional hook to customize anonymous ID generation. | | reuseAnonymousId | false | Reuses one anonymous ID across user changes on the same device. | | personProfiles | PersonProfiles.IDENTIFIED_ONLY | Controls when person profiles are processed: IDENTIFIED_ONLY, ALWAYS, or NEVER. | | setDefaultPersonProperties | true | Includes default device and app properties in feature flag evaluation requests. | | releaseIdentifier | app/version fallback | Release identifier used by error tracking and uploaded ProGuard/R8 mappings. The Android Gradle plugin can inject this automatically. | | tracingHeaders | null | Exact hostnames that should receive PostHog tracing headers when using PostHogOkHttpInterceptor. |

Feature flag options

| Option | Default | Description | | --- | --- | --- | | sendFeatureFlagEvent | true | Sends $feature_flag_called when a feature flag is evaluated. | | featureFlagCalledCacheSize | 1000 | Number of feature flag calls cached for deduplicating $feature_flag_called events. | | preloadFeatureFlags | true | Fetches feature flags automatically during setup. | | evaluationContexts | null | Context tags that constrain which feature flags are evaluated. Available in version 3.29.1+. The legacy evaluationEnvironments option is available in version 3.24.0+. | | onFeatureFlags | null | Callback invoked when feature flags are loaded. |

Product configuration objects

| Option | Default | Description | | --- | --- | --- | | sessionReplay | false | Enables session replay when project settings also allow recording. | | sessionReplayConfig | PostHogSessionReplayConfig() | Configures masking, screenshots, Logcat capture, sampling, and custom drawable conversion. | | logs | PostHogLogsConfig() | Configures Android logs. | | errorTrackingConfig | PostHogErrorTrackingConfig() | Configures error tracking. autoCapture defaults to false; set it to true to autocapture uncaught exceptions when project settings also enable error tracking. | | surveys | false | Internal/experimental native Android survey support. Native Android survey UI is not fully supported or documented yet. | | surveysConfig | PostHogSurveysConfig() | Internal/experimental survey display delegate configuration, primarily for hybrid SDKs. | | bootstrap | null | Seeds identity (distinctId, isIdentifiedId) and feature-flag state (featureFlags, featureFlagPayloads) before the first /flags response. Bootstrapped identity applies to the first session; only enabled flags are served, until the first /flags response replaces them. See SDK bootstrapping. |

Event filtering with beforeSend

Use addBeforeSend to redact, modify, or drop events before they are queued. Return null to drop an event.

config.addBeforeSend { event ->
    event.properties?.remove("password")

    if (event.event == "internal_debug_event") {
        null
    } else {
        event
    }
}

Filtering autocaptured screens

You can stop specific screens from being autocaptured by filtering them in your before-send hook. Return null for any $screen event whose $screen_name matches a screen you don't want to track, and it's dropped before being sent – keeping unwanted screen views out of your event log.

Because it's just a function, you can filter however you like – an ignorelist (drop the screens you name), an allowlist (invert the check to capture only the screens you name), or any custom rule such as a name prefix, a regex, or a check against the event's properties.

val ignoredScreens = setOf("Splash", "Debug")

config.addBeforeSend { event ->
    val screenName = event.properties?.get("$screen_name") as? String
    if (event.event == "$screen" && screenName in ignoredScreens) {
        null
    } else {
        event
    }
}

Push notifications

The Android SDK can register a device for Workflows push notifications and capture when a user opens one. For setup, including automatic and manual registration, capturing opens, opting out, and identity verification, see Push notifications.

FAQ

What Android API level is required?

The Android SDK supports Android API 23 and newer.

Do I need to declare permissions in the AndroidManifest.xml?

Usually, no. The SDK declares android.permission.INTERNET and android.permission.ACCESS_NETWORK_STATE, and Android's manifest merger adds them to your app. The SDK does not declare or require an Android Service.