Instrument Product Analytics
PostHogOfficialCreated by PostHog
- Skill
- Tool integration
- Data and AI
- MIT
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured, multi-step workflow to integrate PostHog product analytics into a wide variety of software projects. It guides the user through detecting the project's framework, installing the appropriate SDK, initializing the service, and strategically placing event capture calls. The skill emphasizes non-intrusive implementation, requiring that new analytics code be added alongside existing logic without altering the project's fundamental architecture. It also covers user identification, error tracking, and secure environment variable management.
What it does
- Detects the project's framework and language to determine the correct PostHog SDK.
- Handles initial SDK installation and initialization based on framework-specific patterns.
- Identifies key user actions and business-critical events for tracking.
- Implements event capture calls and user identification logic.
- Configures environment variables securely for API tokens and host URLs.
- Verifies the integration and performs targeted linting on modified files.
When to use it
- After implementing new features that require tracking for product analytics.
- When reviewing pull requests to ensure meaningful user behaviors are captured.
- During the initial setup of a new project that needs product analytics.
- When migrating or adding analytics to an existing application.
Advantages
- Supports a broad range of frontend, backend, and mobile frameworks.
- Ensures consistent event naming and property usage across the codebase.
- Prioritizes non-breaking changes and minimal impact on existing code structure.
- Automates the complex setup of environment variables and SDK initialization.
Usage examples
- “Add PostHog analytics to my Next.js project.”
- The agent will analyze the project structure, install the PostHog SDK, initialize it in the appropriate client/server files, and prompt you to identify key events to track.
- “I need to track user signups and errors in my Django backend.”
- The agent will locate your authentication logic, add identify calls, implement exception capture, and ensure the PostHog project tokens are managed via environment variables.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/posthog/instrument-product-analytics/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip instrument-product-analytics.zip -d .agents/skills
Documentation by PostHog
Add PostHog product analytics events
Use this skill to add product analytics events (capture calls) that track meaningful user actions in new or changed code. Use it after implementing features or reviewing PRs to ensure key user behaviors are captured. If PostHog is not yet installed, this skill also covers initial SDK setup. Supports any framework or language.
Supported frameworks and languages: Next.js, React Router, Nuxt, Vue, TanStack Start, SvelteKit, Astro, Angular, Django, Flask, FastAPI, Laravel, PHP, Ruby on Rails, Go, Elixir, Android, iOS, Flutter, React Native, Expo, and more.
Instructions
Follow these steps IN ORDER:
STEP 1: Analyze the codebase and detect the platform.
Look for dependency files (package.json, pubspec.yaml, Podfile, Package.swift, requirements.txt, Gemfile, composer.json, go.mod, mix.exs, etc.) to determine the framework and language.
Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, go.sum, pubspec.lock, Podfile.lock, Package.resolved, mix.lock) to determine the package manager.
Check for existing PostHog setup. If PostHog is already installed and initialized, skip to STEP 5.
STEP 2: Research integration. (Skip if PostHog is already set up.) 2.1. Find the reference file below that matches the detected framework — it is the source of truth for SDK initialization, provider setup, and event capture patterns. Read it now. 2.2. If no reference matches, fall back to your general knowledge and web search. Use posthog.com/docs as the primary search source.
STEP 3: Install the PostHog SDK. (Skip if PostHog is already set up.)
Add the PostHog SDK package for the detected platform. Do not manually edit package.json — use the package manager's install command.
STEP 4: Initialize PostHog. (Skip if PostHog is already set up.)
Follow the framework reference for where and how to initialize. This varies significantly by framework (e.g., instrumentation-client.ts for Next.js 15.3+, AppConfig.ready() for Django, create_app() for Flask).
STEP 5: Plan event tracking.
From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events.
Also look for files related to login that could be used for identifying users, along with error handling.
Find any existing
posthog.capture()code. Make note of event name formatting. Don't duplicate existing events; supplement them.Track actions only, not pageviews (those can be captured automatically). Exceptions can be made for "viewed"-type events at the top of a conversion funnel.
Server-side events are REQUIRED if the project includes any instrumentable server-side code (API routes, server actions, webhook handlers, payment/checkout completion, authentication endpoints).
STEP 6: Implement event capture.
For each planned event, add
posthog.capture()calls with useful properties.If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it.
Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.
You must read a file immediately before attempting to write it.
STEP 7: Identify users.
Add PostHog
identify()calls on the client side during login and signup events. Use the contents of login and signup forms to identify users on submit.If both frontend and backend exist, pass the client-side session and distinct ID using
X-POSTHOG-DISTINCT-IDandX-POSTHOG-SESSION-IDheaders to the server-side code. On the server side, make sure events have a matching distinct ID.
STEP 8: Add error tracking.
Add PostHog exception capture error tracking to relevant files, particularly around critical user flows and API boundaries.
STEP 9: Set up environment variables.
Check if the project already has PostHog environment variables configured (e.g. in
.env,.env.local, or framework-specific env files). If valid values already exist, skip this step.If the PostHog project token is missing, use the PostHog MCP server's
projects-gettool to retrieve the project'sapi_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.For the PostHog host URL: check the
projects-getMCP response for aregionfield —USmaps tohttps://us.i.posthog.com,EUmaps tohttps://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.Write these values to the appropriate env file using the framework's naming convention.
Reference these environment variables in code instead of hardcoding them.
STEP 10: Verify and clean up.
Check the project for errors. Look for type checking or build scripts in package.json.
Ensure any components created were actually used.
Run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Never run formatting or linting across the entire project's codebase.
Reference files
references/EXAMPLE-next-app-router.md- next-app-router example project codereferences/EXAMPLE-next-pages-router.md- next-pages-router example project codereferences/EXAMPLE-react-react-router-6.md- react-react-router-6 example project codereferences/EXAMPLE-react-react-router-7-framework.md- react-react-router-7-framework example project codereferences/EXAMPLE-react-react-router-7-data.md- react-react-router-7-data example project codereferences/EXAMPLE-react-react-router-7-declarative.md- react-react-router-7-declarative example project codereferences/EXAMPLE-nuxt-3-6.md- nuxt-3-6 example project codereferences/EXAMPLE-nuxt-4.md- nuxt-4 example project codereferences/EXAMPLE-vue-3.md- vue-3 example project codereferences/EXAMPLE-react-tanstack-router-file-based.md- react-tanstack-router-file-based example project codereferences/EXAMPLE-react-tanstack-router-code-based.md- react-tanstack-router-code-based example project codereferences/EXAMPLE-tanstack-start.md- tanstack-start example project codereferences/EXAMPLE-sveltekit.md- sveltekit example project codereferences/EXAMPLE-astro-static.md- astro-static example project codereferences/EXAMPLE-astro-view-transitions.md- astro-view-transitions example project codereferences/EXAMPLE-astro-ssr.md- astro-ssr example project codereferences/EXAMPLE-astro-hybrid.md- astro-hybrid example project codereferences/EXAMPLE-angular.md- angular example project codereferences/EXAMPLE-django.md- django example project codereferences/EXAMPLE-flask.md- flask example project codereferences/EXAMPLE-fastapi.md- fastapi example project codereferences/EXAMPLE-python.md- python example project codereferences/EXAMPLE-laravel.md- laravel example project codereferences/EXAMPLE-php.md- php example project codereferences/EXAMPLE-ruby-on-rails.md- ruby-on-rails example project codereferences/EXAMPLE-ruby.md- ruby example project codereferences/EXAMPLE-android.md- android example project codereferences/EXAMPLE-swift.md- swift example project codereferences/EXAMPLE-react-native.md- react-native example project codereferences/EXAMPLE-expo.md- expo example project codereferences/next-js.md- Next.jsreferences/react-router-v6.md- React router v6references/react-router-v7-framework-mode.md- React router v7 framework mode (remix v3)references/react-router-v7-data-mode.md- React router v7 data modereferences/react-router-v7-declarative-mode.md- React router v7 declarative modereferences/nuxt-js-3-6.md- Nuxt.js (v3.0 to v3.6)references/nuxt-js.md- Nuxt.jsreferences/vue-js.md- Vue.jsreferences/tanstack-start.md- Tanstack startreferences/svelte.md- Sveltereferences/astro.md- Astroreferences/angular.md- Angularreferences/django.md- Djangoreferences/flask.md- Flaskreferences/python.md- Pythonreferences/posthog-python.md- PostHog python SDKreferences/dotnet.md- .netreferences/elixir.md- Elixirreferences/go.md- Goreferences/laravel.md- Laravelreferences/php.md- Phpreferences/ruby-on-rails.md- Ruby on railsreferences/ruby.md- Rubyreferences/android.md- Androidreferences/ios.md- Iosreferences/usage.md- Ios SDK usagereferences/configuration.md- Ios SDK configurationreferences/flutter.md- Flutterreferences/react-native.md- React nativereferences/identify-users.md- Identify usersreferences/COMMANDMENTS.md- Framework-specific rules the integration must follow
Each framework reference contains SDK-specific installation, initialization, and usage patterns. Find the one matching the user's stack.
Key principles
Environment variables: Always use environment variables for PostHog keys. Never hardcode them.
Minimal changes: Add PostHog code alongside existing integrations. Don't replace or restructure existing code.
Match the docs: Follow the framework reference's initialization and capture patterns exactly.
Files
- ATTRIBUTION.mdAdded by AutoGineer970 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md9.6 KiB
- references/COMMANDMENTS.md1.5 KiB
- references/EXAMPLE-android.md49.8 KiB
- references/EXAMPLE-angular.md23.1 KiB
- references/EXAMPLE-astro-hybrid.md27.5 KiB
- references/EXAMPLE-astro-ssr.md27.6 KiB
- references/EXAMPLE-astro-static.md19.6 KiB
- references/EXAMPLE-astro-view-transitions.md23.3 KiB
- references/EXAMPLE-django.md30.7 KiB
- references/EXAMPLE-expo.md35.1 KiB
- references/EXAMPLE-fastapi.md40.9 KiB
- references/EXAMPLE-flask.md32.4 KiB
- references/EXAMPLE-laravel.md59.3 KiB
- references/EXAMPLE-next-app-router.md17.6 KiB
- references/EXAMPLE-next-pages-router.md19.1 KiB
- references/EXAMPLE-nuxt-3-6.md22.3 KiB
- references/EXAMPLE-nuxt-4.md28.9 KiB
- references/EXAMPLE-php.md13.0 KiB
- references/EXAMPLE-python.md11.6 KiB
- references/EXAMPLE-react-native.md46.0 KiB
- references/EXAMPLE-react-react-router-6.md13.5 KiB
- references/EXAMPLE-react-react-router-7-data.md20.1 KiB
- references/EXAMPLE-react-react-router-7-declarative.md15.0 KiB
- references/EXAMPLE-react-react-router-7-framework.md32.5 KiB
- references/EXAMPLE-react-tanstack-router-code-based.md19.6 KiB
- references/EXAMPLE-react-tanstack-router-file-based.md18.3 KiB
- references/EXAMPLE-ruby-on-rails.md38.0 KiB
- references/EXAMPLE-ruby.md10.0 KiB
- references/EXAMPLE-sveltekit.md18.6 KiB
- references/EXAMPLE-swift.md18.8 KiB
- references/EXAMPLE-tanstack-start.md29.9 KiB
- references/EXAMPLE-vue-3.md17.9 KiB
- references/android.md33.3 KiB
- references/angular.md16.5 KiB
- references/astro.md15.8 KiB
- references/configuration.md17.2 KiB
- references/django.md14.9 KiB
- references/dotnet.md25.8 KiB
- references/elixir.md17.6 KiB
- references/flask.md8.1 KiB
- references/flutter.md42.8 KiB
- references/go.md20.1 KiB
- references/identify-users.md12.2 KiB
- references/ios.md8.0 KiB
- references/laravel.md13.1 KiB
- references/next-js.md18.3 KiB
- references/nuxt-js-3-6.md11.4 KiB
- references/nuxt-js.md15.1 KiB
- references/php.md23.7 KiB
- references/posthog-python.md69.3 KiB
- references/python.md52.2 KiB
- references/react-native.md59.9 KiB
- references/react-router-v6.md13.6 KiB
- references/react-router-v7-data-mode.md13.5 KiB
- references/react-router-v7-declarative-mode.md13.7 KiB
- references/react-router-v7-framework-mode.md20.2 KiB
- references/ruby-on-rails.md19.7 KiB
- references/ruby.md25.5 KiB
- references/svelte.md14.6 KiB
- references/tanstack-start.md12.8 KiB
- references/usage.md29.2 KiB
- references/vue-js.md13.4 KiB
references/android.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
Android
Canonical URL: https://posthog.com/docs/libraries/android
Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use
https://eu.posthog.cominstead ofhttps://us.posthog.com(app host for links).
On this page
Install with the wizard
Installation
Capturing events
Identifying users
Get the current user's distinct ID
Tracing headers
Alias
Anonymous and identified events
Setting person properties
Super Properties
Opt out of data capture
Flush
Reset after logout
Feature Flags
Experiments (A/B tests)
Group analytics
Error tracking
Logs
Session replay
Surveys
Offline behavior
Debug mode
All configuration options
What Android API level is required?
Do I need to declare permissions in the AndroidManifest.xml?
It uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your mobile app.
Install with the wizard
Run this command in your project directory to add PostHog to your Android project. The wizard detects your framework, installs the SDK, and sets up your first events.
npx @posthog/wizard
Or set it up manually by following the rest of this guide.
Installation
The best way to install the PostHog Android library is with a build system like Gradle. This ensures you can easily upgrade to the latest versions.
All you need to do is add the posthog-android module to your App's build.gradle or build.gradle.kts:
app/build.gradle
dependencies {
implementation 'com.posthog:posthog-android:3.+'
}app/build.gradle.kts
dependencies {
implementation("com.posthog:posthog-android:3.+")
}Configuration
The best place to initialize the client is in your Application subclass.
import android.app.Application
import com.posthog.android.PostHogAndroid
import com.posthog.android.PostHogAndroidConfig
class SampleApp : Application() {
companion object {
const val POSTHOG_API_KEY = "<ph_project_token>"
// usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
const val POSTHOG_HOST = "https://us.i.posthog.com"
}
override fun onCreate() {
super.onCreate()
val config = PostHogAndroidConfig(
apiKey = POSTHOG_API_KEY,
host = POSTHOG_HOST
)
PostHogAndroid.setup(this, config)
}
}Capturing events
You can send custom events using capture:
import com.posthog.PostHog
PostHog.capture(event = "user_signed_up")Tip: We recommend using a
[object] [verb]format for your event names, where[object]is the entity that the behavior relates to, and[verb]is the behavior itself. For example,project created,user signed up, orinvite sent.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
import com.posthog.PostHog
PostHog.capture(
event = "user_signed_up",
properties = mapOf(
"login_type" to "email",
"is_free_trial" to true
)
)Autocapture
PostHog autocapture automatically tracks the following events for you:
Application Opened - when the app is opened from a closed state or when the app comes to the foreground. (e.g. from the app switcher)
Deep Link Opened - when the app is opened from a deep link.
Application Backgrounded - when the app is sent to the background by the user.
Application Installed - when the app is installed.
Application Updated - when the app is updated.
$screen - when the user navigates. (if using
android.app.Activity)$exception - when uncaught exception autocapture is enabled. To use this, enable Android error tracking and exception autocapture in the SDK config.
Capturing screen views
With captureScreenViews = true, PostHog will try to record all screen changes automatically.
The screenTitle will be the <activity>'s android:label, if not set it'll fallback to the <application>'s android:label or the <activity>'s android:name.
<activity
android:name="com.example.app.ChildActivity"
android:label="@string/title_child_activity"
...
</activity>If you want to manually send a new screen capture event, use the screen function.
This function requires a screenTitle. You may also pass in an optional properties object.
import com.posthog.PostHog
PostHog.screen(
screenTitle = "Dashboard",
properties = mapOf(
"background" to "blue",
"hero" to "superhog"
)
)Identifying users
We highly recommend reading our section on Identifying users to better understand how to correctly use this method.
Using identify, you can associate events with specific users. This enables you to gain full insights as to how they're using your product across different sessions, devices, and platforms.
An identify call has the following arguments:
distinctId: Required. A unique identifier for your user. Typically either their email or database ID.
userProperties: Optional. A dictionary with key:value pairs to set the person properties
userPropertiesSetOnce: Optional. Similar to
userProperties. See the difference betweenuserPropertiesanduserPropertiesSetOnce
import com.posthog.PostHog
PostHog.identify(
distinctId = distinctID,
userProperties = mapOf(
"name" to "Max Hedgehog",
"email" to "[email protected]"
),
userPropertiesSetOnce = mapOf(
"date_of_first_log_in" to "2024-03-01"
),
)You should call identify as soon as you're able to. Typically, this is after your user logs in. This ensures that events sent during your user's sessions are correctly associated with them.
When you call identify, all previously tracked anonymous events will be linked to the user.
Get the current user's distinct ID
You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called identify for a user or not.
To do this, call distinctId(). This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify().
Tracing headers
Use tracingHeaders to connect Android network requests to backend events, errors, and LLM traces captured by a server-side PostHog SDK. Tracing headers are added by the PostHogOkHttpInterceptor, so install the interceptor on each OkHttpClient whose requests should include PostHog context.
import com.posthog.PostHogOkHttpInterceptor
import com.posthog.android.PostHogAndroid
import com.posthog.android.PostHogAndroidConfig
import okhttp3.OkHttpClient
val config = PostHogAndroidConfig(
apiKey = POSTHOG_API_KEY,
host = POSTHOG_HOST,
).apply {
tracingHeaders = listOf("api.example.com")
}
PostHogAndroid.setup(this, config)
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(PostHogOkHttpInterceptor())
.build()Hostnames are matched exactly and should not include protocols, paths, ports, or wildcard subdomains. Matching OkHttp requests include X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID when those values are available.
Alias
Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.
In this case, you can use alias to assign another distinct ID to the same user.
/**
* Create an alias for the current user.
*/
PostHog.alias("distinct_id")We strongly recommend reading our docs on alias to best understand how to correctly use this method.
Anonymous and identified events
PostHog captures two types of events: anonymous and identified
Identified events enable you to attribute events to specific users, and attach person properties. They're best suited for logged-in users.
Scenarios where you want to capture identified events are:
Tracking logged-in users in B2B and B2C SaaS apps
Doing user segmented product analysis
Growth and marketing teams wanting to analyze the complete conversion lifecycle
Anonymous events are events without individually identifiable data. They're best suited for web analytics or apps where users aren't logged in.
Scenarios where you want to capture anonymous events are:
Tracking a marketing website
Content-focused sites
B2C apps where users don't sign up or log in
Under the hood, the key difference between identified and anonymous events is that for identified events we create a person profile for the user, whereas for anonymous events we do not.
Important: Due to the reduced cost of processing them, anonymous events can be up to 4x cheaper than identified ones, so we recommended you only capture identified events when needed.
How to capture anonymous events
The Android SDK captures anonymous events by default. However, this may change depending on your personProfiles config when initializing PostHog:
personProfiles = PersonProfiles.IDENTIFIED_ONLY(recommended) (default) - Anonymous events are captured by default. PostHog only captures identified events for users where person profiles have already been created.personProfiles = PersonProfiles.ALWAYS- Capture identified events for all events.personProfiles = PersonProfiles.NEVER- Capture anonymous events for all events.
For example:
val config = PostHogAndroidConfig(
apiKey = POSTHOG_API_KEY,
host = POSTHOG_HOST,
).apply {
personProfiles = PersonProfiles.IDENTIFIED_ONLY
}How to capture identified events
If you've set the personProfiles config to IDENTIFIED_ONLY (the default option), anonymous events are captured by default. Then, to capture identified events, call any of the following functions:
When you call any of these functions, it creates a person profile for the user. Once this profile is created, all subsequent events for this user will be captured as identified events.
Alternatively, you can set personProfiles to ALWAYS to capture identified events by default.
Setting person properties
To set properties on your users via an event, you can leverage the event properties userProperties and userPropertiesSetOnce.
When capturing an event, you can pass a property called userProperties as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.
import com.posthog.PostHog
PostHog.capture(
event = "button_b_clicked",
properties = mapOf("color" to "blue"),
userProperties = mapOf(
"string" to "value1",
"integer" to 2
)
)userPropertiesSetOnce works just like userProperties, except that it will only set the property if the user doesn't already have that property set.
import com.posthog.PostHog
PostHog.capture(
event = "button_b_clicked",
properties = mapOf("color" to "blue"),
userPropertiesSetOnce = mapOf(
"string" to "value1",
"integer" to 2
)
)Super Properties
Super Properties are properties associated with events that are set once and then sent with every capture call, be it a $screen, or anything else.
They are set using PostHog.register, which takes a key and value, and they persist across sessions.
For example, take a look at the following call:
import com.posthog.PostHog
PostHog.register("team_id", 22)The call above ensures that every event sent by the user will include "team_id": 22. This way, if you filtered events by property using team_id = 22, it would display all events captured on that user after the PostHog.register call, since they all include the specified Super Property.
However, please note that this does not store properties against the User, only against their events. To store properties against the User object, you should use PostHog.identify. More information on this can be found on the Sending User Information section.
Removing stored Super Properties
Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant. In order to stop sending a Super Property with events, you can use PostHog.unregister, like so:
import com.posthog.PostHog
PostHog.unregister("team_id")This will remove the Super Property and subsequent events will not include it.
If you are doing this as part of a user logging out you can instead simply use PostHog.reset which takes care of clearing all stored Super Properties and more.
Opt out of data capture
You can completely opt-out users from data capture. To do this, there are two options:
Opt users out by default by setting
optOuttotruein your PostHog config:
val config = PostHogAndroidConfig(
apiKey = "<ph_project_token>",
host = "https://us.i.posthog.com"
)
config.optOut = true
PostHogAndroid.setup(this, config)Opt users out on a per-person basis by calling
optOut():
PostHog.optOut()Similarly, you can opt users in:
PostHog.optIn()To check if a user is opted out:
PostHog.isOptOut()Flush
You can configure how many events queue before flushing with flushAt. Setting this to 1 will send events immediately and will use more battery. The default is 20.
You can also configure the flush interval with flushIntervalSeconds (default 30), after which queued events are sent regardless of how many have been gathered:
import com.posthog.android.PostHogAndroidConfig
val config = PostHogAndroidConfig(apiKey = POSTHOG_API_KEY, host = POSTHOG_HOST).apply {
flushAt = 20
flushIntervalSeconds = 30
}You can also manually flush the queue to start sending events immediately instead of waiting for the next batch:
import com.posthog.PostHog
PostHog.flush()Flushing is best-effort and asynchronous – it starts sending queued events in the background but doesn't wait for the request to finish, so it isn't a delivery guarantee.
Reset after logout
To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out.
import com.posthog.PostHog
PostHog.reset()Feature Flags
PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.
Boolean feature flags
import com.posthog.PostHog
val result = PostHog.getFeatureFlagResult("flag-key")
if (result?.enabled == true) {
// Do something differently for this user
// Optional: fetch the payload from the same evaluation result
val matchedFlagPayload = result.payload
}Multivariate feature flags
import com.posthog.PostHog
val result = PostHog.getFeatureFlagResult("flag-key")
if (result?.variant == "variant-key") { // replace "variant-key" with the key of your variant
// Do something differently for this user
// Optional: fetch the payload from the same evaluation result
val matchedFlagPayload = result.payload
}Inspecting all feature flags
You can inspect all currently loaded feature flags with PostHog.getAllFeatureFlags(). It returns each flag's key, enabled state, variant, and payload, and does not send a $feature_flag_called event, so calling it won't affect your experiment results or flag usage analytics:
import com.posthog.PostHog
PostHog.getAllFeatureFlags()?.forEach { flag ->
println("${flag.key} ${flag.enabled} ${flag.variant} ${flag.payload}")
}Ensuring flags are loaded before usage
Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.
This means that for most screens, the feature flags are available immediately – except for the first time a user visits.
To handle this, you can use the onFeatureFlags callback to wait for the feature flag request to finish:
import com.posthog.PostHog
import com.posthog.android.PostHogAndroidConfig
import com.posthog.PostHogOnFeatureFlags
// During SDK initialization
val config = PostHogAndroidConfig(apiKey = "<ph_project_token>").apply {
onFeatureFlags = PostHogOnFeatureFlags {
if (PostHog.isFeatureEnabled("flag-key")) {
// do something
}
}
}
// And/or after the SDK is initialized
PostHog.reloadFeatureFlags {
if (PostHog.isFeatureEnabled("flag-key")) {
// do something
}
}Reloading feature flags
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:
import com.posthog.PostHog
PostHog.reloadFeatureFlags()Tracking feature usage
To track when someone sees or interacts with a feature, use captureFeatureView and captureFeatureInteraction.
import com.posthog.PostHog
PostHog.captureFeatureView("flag-key", flagVariant = "variant-key")
PostHog.captureFeatureInteraction("flag-key", flagVariant = "variant-key")Bootstrapping flags
Since there is a delay between initializing PostHog and fetching feature flags, feature flags are not always available immediately. This makes them unusable if you want to do something like redirecting a user to a different page based on a feature flag.
To have your feature flags available immediately, you can initialize PostHog with precomputed values until it has had a chance to fetch them. This is called bootstrapping. After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones.
Set config.bootstrap before calling setup() to seed identity and flag values before the first /flags response (requires Android SDK 3.55.0+):
import com.posthog.PostHogBootstrapConfig
val config = PostHogAndroidConfig(apiKey = POSTHOG_API_KEY, host = POSTHOG_HOST)
config.bootstrap = PostHogBootstrapConfig(
distinctId = "distinct_id_of_your_user",
isIdentifiedId = true,
featureFlags = mapOf(
"flag-1" to true,
"variant-flag" to "control"
)
)
PostHogAndroid.setup(this, config)Bootstrapped identity applies during setup. On a fresh install, setting it before
setup()means events captured synchronously during initialization (likeApplication Installed) carry your distinct ID instead of the SDK-generated UUID.An anonymous bootstrap (
isIdentifiedId: false, the default) seeds the anonymous ID only when none is persisted yet. Once an anonymous ID exists on disk, or the person has been identified, the SDK ignores it.An identified bootstrap (
isIdentifiedId: true) is for a signed-in identity available to your app (for example, from a backend session token). On a fresh install, it seeds the distinct ID, marks the person identified, and generates a separate device ID. On a returning install, a matching anonymous ID is marked identified without emitting$identify; a different anonymous ID is merged viaidentify()when person profiles are enabled. This emits$identifyunless capturing is opted out. A different, already-identified person is left untouched.
Bootstrapped flags are served until the first
/flagsresponse, then replaced. A complete/flagsresponse takes over entirely, so bootstrapped-only keys don't persist past it. Only enabled flags are seeded: atrueboolean or a non-empty variant string. Afalseor empty value is dropped, matching posthog-js. Seed payloads with the separatefeatureFlagPayloadsoption. Flag values and payloads must be JSON-serializable, or they're dropped. Bootstrapped flags are cleared onreset().
The feature-flags-loaded signal fires as soon as bootstrapped flags are applied, so startup logic can read them immediately. These SDKs don't support the sessionID bootstrap option. When person profiles are set to never, the SDK preserves a different anonymous identity instead of merging it into an identified bootstrap.
See the SDK bootstrapping guide for the cross-SDK overview.
Experiments (A/B tests)
Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:
import com.posthog.PostHog
if (PostHog.getFeatureFlag("experiment-feature-flag-key") == "variant-name") {
// do something
}It's also possible to run experiments without using feature flags.
Group analytics
Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). Read the Group Analytics guide for more information.
Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more on the pricing page.
Associate the events for this session with a group
import com.posthog.PostHog
// organization is the group type, company_id_in_your_db is the group ID
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
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
maxQueueSizein 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.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- PostHog
- Publisher
- PostHog (Official)
- Source
- PostHog/skills · skills/omnibus/instrument-product-analytics · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by PostHog or PostHog.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-product-analytics.zip