Android

Contents

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.

Learn more

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:

dependencies {
implementation 'com.posthog:posthog-android:4.+'
}

Configuration

The best place to initialize the client is in your Application subclass.

Kotlin
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(
projectToken = POSTHOG_API_KEY,
host = POSTHOG_HOST
)
PostHogAndroid.setup(this, config)
}
}

Capturing events

You can send custom events using capture:

Kotlin
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, or invite sent.

Setting event properties

Optionally, you can include additional information with the event by including a properties object:

Kotlin
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.

XML
<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.

Kotlin
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:

Kotlin
import com.posthog.PostHog
PostHog.identify(
distinctId = distinctID,
userProperties = mapOf(
"name" to "Max Hedgehog",
"email" to "max@hedgehogmail.com"
),
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.

Kotlin
import com.posthog.PostHogOkHttpInterceptor
import com.posthog.android.PostHogAndroid
import com.posthog.android.PostHogAndroidConfig
import okhttp3.OkHttpClient
val config = PostHogAndroidConfig(
projectToken = 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.

Kotlin
/**
* 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:

  1. 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.

  2. personProfiles = PersonProfiles.ALWAYS - Capture identified events for all events.

  3. personProfiles = PersonProfiles.NEVER - Capture anonymous events for all events.

For example:

Kotlin
val config = PostHogAndroidConfig(
projectToken = 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.

Kotlin
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.

Kotlin
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:

Kotlin
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:

Kotlin
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:

  1. Opt users out by default by setting optOut to true in your PostHog config:
Kotlin
val config = PostHogAndroidConfig(
projectToken = "<ph_project_token>",
host = "https://us.i.posthog.com"
)
config.optOut = true
PostHogAndroid.setup(this, config)
  1. Opt users out on a per-person basis by calling optOut():
Kotlin
PostHog.optOut()

Similarly, you can opt users in:

Kotlin
PostHog.optIn()

To check if a user is opted out:

Kotlin
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:

Kotlin
import com.posthog.android.PostHogAndroidConfig
val config = PostHogAndroidConfig(projectToken = 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:

Kotlin
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.

Kotlin
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

Kotlin
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

Kotlin
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:

Kotlin
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, register a listener with PostHog.onFeatureFlags() before you set up the SDK, so it also gets the first load:

Kotlin
import com.posthog.PostHog
import com.posthog.android.PostHogAndroid
import com.posthog.android.PostHogAndroidConfig
// Before setup
val subscription = PostHog.onFeatureFlags { loaded ->
if (!loaded.errorsLoading && PostHog.getFeatureFlag("flag-key") == "test") {
// do something
}
}
PostHogAndroid.setup(context, PostHogAndroidConfig(projectToken = "<ph_project_token>"))
// Later, stop listening
subscription.unsubscribe()
// And/or after the SDK is initialized
PostHog.reloadFeatureFlags { loaded ->
if (!loaded.errorsLoading && PostHog.isFeatureEnabled("flag-key")) {
// do something
}
}

Both callbacks also run when loading fails. loaded is a PostHogFeatureFlagsLoaded with flags (the keys of the enabled flags), variants (their values), and errorsLoading (whether the load failed, in which case the values are the last known ones).

The listener runs on the main thread after every flag load, and it also gets the current values if flags have already loaded. The reloadFeatureFlags() callback runs on a background thread, so switch to the main thread before touching UI.

Read the value with getFeatureFlag when you act on it. It captures $feature_flag_called, which experiments use to record exposure, and reading loaded.variants doesn't.

PostHog.onFeatureFlags() and the loaded argument require version 4.0 or later. On 3.x, set onFeatureFlags = PostHogOnFeatureFlags { … } on the config instead, and the callbacks take no arguments.

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:

Kotlin
import com.posthog.PostHog
PostHog.reloadFeatureFlags()

Tracking feature usage

To track when someone sees or interacts with a feature, use captureFeatureView and captureFeatureInteraction.

Kotlin
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+):

Kotlin
import com.posthog.PostHogBootstrapConfig
val config = PostHogAndroidConfig(projectToken = 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 (like Application 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 via identify() when person profiles are enabled. This emits $identify unless capturing is opted out. A different, already-identified person is left untouched.
  • Bootstrapped flags are served until the first /flags response, then replaced. A complete /flags response takes over entirely, so bootstrapped-only keys don't persist past it. Only enabled flags are seeded: a true boolean or a non-empty variant string. A false or empty value is dropped, matching posthog-js. Seed payloads with the separate featureFlagPayloads option. Flag values and payloads must be JSON-serializable, or they're dropped. Bootstrapped flags are cleared on reset().

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:

Kotlin
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
Kotlin
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
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:posthog-android@3.46.0 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.

Kotlin
val config = PostHogAndroidConfig(projectToken = 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.

Kotlin
import com.posthog.PersonProfiles
import com.posthog.android.PostHogAndroidConfig
val config = PostHogAndroidConfig(
projectToken = POSTHOG_API_KEY,
host = POSTHOG_HOST
).apply {
captureApplicationLifecycleEvents = true
captureScreenViews = true
captureDeepLinks = true
flushAt = 20
maxQueueSize = 1000
maxBatchSize = 50
pushNotificationSubscriptionMaxRetries = 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

OptionDefaultDescription
captureApplicationLifecycleEventstrueCaptures Application Installed, Application Updated, Application Opened, and Application Backgrounded.
captureScreenViewstrueCaptures $screen for foreground android.app.Activity screens.
captureDeepLinkstrueCaptures Deep Link Opened with URL/query/referrer properties.

Core options

OptionDefaultDescription
debugfalseEnables verbose SDK logs in Logcat. You can also call PostHog.debug(true).
optOutfalsePrevents data capture when enabled. You can also call PostHog.optOut() and PostHog.optIn().
flushAt20Number of queued events that triggers a flush.
maxQueueSize1000Maximum number of events kept across memory and disk before FIFO eviction.
maxBatchSize50Maximum number of events sent in one batch request. In version 4.0+, a request also carries at most about 5 MiB of events, and the SDK sends as soon as that much is queued.
pushNotificationSubscriptionMaxRetries3Maximum retry attempts for push-subscription registration failures. It does not apply to event, session recording, or log ingestion.
flushIntervalSeconds30Maximum delay before queued data is flushed.
encryptionnullOptional PostHogEncryption implementation for encrypting persisted queued events.
proxynullOptional java.net.Proxy for PostHog API requests.
compressionPostHogCompression.GZIPCompresses request bodies sent to PostHog. Set it to PostHogCompression.NONE if something between the app and PostHog alters compressed bodies. captureAi requests use captureAiCompression instead. Has no effect when you set your own httpClient.
getAnonymousIdgenerated UUIDOptional hook to customize anonymous ID generation.
reuseAnonymousIdfalseReuses one anonymous ID across user changes on the same device.
personProfilesPersonProfiles.IDENTIFIED_ONLYControls when person profiles are processed: IDENTIFIED_ONLY, ALWAYS, or NEVER.
setDefaultPersonPropertiestrueIncludes default device and app properties in feature flag evaluation requests.
releaseIdentifierapp/version fallbackRelease identifier used by error tracking and uploaded ProGuard/R8 mappings. The Android Gradle plugin can inject this automatically.
tracingHeadersnullExact hostnames that should receive PostHog tracing headers when using PostHogOkHttpInterceptor.

Feature flag options

OptionDefaultDescription
sendFeatureFlagEventtrueSends $feature_flag_called when a feature flag is evaluated.
featureFlagCalledCacheSize1000Number of feature flag calls cached for deduplicating $feature_flag_called events.
preloadFeatureFlagstrueFetches feature flags automatically during setup.
evaluationContextsnullContext tags that constrain which feature flags are evaluated. Available in version 3.29.1+. The legacy evaluationEnvironments option was available in version 3.24.0+ and removed in 4.0.

Product configuration objects

OptionDefaultDescription
sessionReplayfalseEnables session replay when project settings also allow recording.
sessionReplayConfigPostHogSessionReplayConfig()Configures masking, screenshot settings, Logcat capture, and sampling.
logsPostHogLogsConfig()Configures Android logs.
errorTrackingConfigPostHogErrorTrackingConfig()Configures error tracking. autoCapture defaults to false; set it to true to autocapture uncaught exceptions when project settings also enable error tracking.
surveysfalseInternal/experimental native Android survey support. Native Android survey UI is not fully supported or documented yet.
surveysConfigPostHogSurveysConfig()Internal/experimental survey display delegate configuration, primarily for hybrid SDKs.
bootstrapnullSeeds 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.

Kotlin
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.

Kotlin
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.

Upgrading from version 3 to version 4

Version 4.0 removes APIs deprecated in 3.x, sends events to capture v1, and always records session replay as screenshots. For every change, with before and after code, see the migration guide.

Requirements

Update posthog-android to 4.+. If you only depend on posthog-android-surveys-compose, declare com.posthog:posthog-android:4.+ in your build so Gradle resolves 4.0. If you depend on core posthog directly, update it in the same change: core is now 7.0 and isn't binary compatible with SDKs built against 6.x. If the same project also uses posthog-server, update it too.

The minimum Android API level (23), Java bytecode target (Java 8), and Kotlin compatibility (2.0) are unchanged.

React Native, Flutter, and Kotlin Multiplatform apps get this SDK through their PostHog package. Upgrade that package instead of adding posthog-android 4.0 yourself.

Removed APIs

These are compile errors:

RemovedUse instead
apiKey, PostHogAndroidConfig(apiKey = …)projectToken
propertiesSanitizer, PostHogPropertiesSanitizeraddBeforeSend
evaluationEnvironmentsevaluationContexts
getFeatureFlagPayload()getFeatureFlagResult(key, sendFeatureFlagEvent = false)?.payload
defaultValue on getFeatureFlag()getFeatureFlag(key) ?: default
PostHogConfig.onFeatureFlagsPostHog.onFeatureFlags() before setup()
PostHogOnFeatureFlagsPostHogFeatureFlagsCallback
PostHogSessionReplayConfig.debouncerDelayMsthrottleDelayMs
PostHogSessionReplayConfig.screenshot, drawableConverter, PostHogDrawableConverterNothing – replay always records screenshots
remoteConfigNothing – remote config always loads
maxRetriespushNotificationSubscriptionMaxRetries

getFeatureFlagResult() sends $feature_flag_called by default and getFeatureFlagPayload() never did, so pass sendFeatureFlagEvent = false to keep your event volume and experiment exposures unchanged. It also has no default value parameter, so add ?: yourDefault if you need one.

Classes that implement PostHogInterface, such as test fakes, need updating. The migration guide lists the changed methods.

Helpers in com.posthog.internal, com.posthog.android.internal, and com.posthog.android.replay.internal that were marked @PostHogInternal are no longer public. Apps that don't use @PostHogInternal APIs aren't affected.

Feature flag callbacks

PostHogConfig.onFeatureFlags is removed, so call PostHog.onFeatureFlags() before setup() instead. The listener and reloadFeatureFlags() now receive a PostHogFeatureFlagsLoaded:

Kotlin
val mainHandler = Handler(Looper.getMainLooper())
// Version 3
config.onFeatureFlags = PostHogOnFeatureFlags {
mainHandler.post { refreshUi() }
}
// Version 4, before PostHogAndroid.setup()
PostHog.onFeatureFlags { loaded ->
if (!loaded.errorsLoading) {
refreshUi()
}
}

The listener returns a subscription you can unsubscribe(), and it differs from the removed option in three ways:

  • It runs on the main thread. The option ran on a background thread.
  • Bootstrapped flags arrive just after setup() is called, not synchronously inside it.
  • A reload on a disabled SDK doesn't call listeners. reloadFeatureFlags(callback) still gets errorsLoading = true in that case.

The reloadFeatureFlags() callback still runs on a background thread, so switch to the main thread before touching UI. See ensuring flags are loaded before usage.

A trailing lambda such as PostHog.reloadFeatureFlags { mainHandler.post { refreshUi() } } still compiles, so check whether it should read errorsLoading. The callback also runs after a failed load.

Event options and AI events

capture, screen, identify, setPersonProperties, alias, group, and captureException take a new options argument as their last parameter. Use it for capture settings such as process_person_profile and cookieless_mode, which 3.x read from $-prefixed properties. The legacy properties still work.

Kotlin
// Version 3
PostHog.capture("signed_up", properties = mapOf("\$process_person_profile" to false))
// Version 4
PostHog.capture("signed_up", options = mapOf("process_person_profile" to false))

Java callers pass the new trailing options argument, or null. In beforeSend, read and edit options through event.options.

captureAi sends AI events such as $ai_generation to PostHog's AI endpoint, on their own queue. It takes the same arguments as capture and returns the event's UUID, or null if the event isn't queued.

Kotlin
PostHog.captureAi(
"\$ai_generation",
properties = mapOf("\$ai_model" to "gpt-5", "\$ai_trace_id" to traceId),
)

If you self-host PostHog or use your own proxy, make sure /i/v1/ai/events is served before you use captureAi.

Behavior changes

These don't fail the build:

  • getFeatureFlag()'s second parameter is now sendFeatureFlagEvent. getFeatureFlag("flag-key", true) still compiles, but true no longer means the default value. A disabled SDK returns null instead of your default, and $feature_flag_called no longer reports a fallback as the flag's value.
  • Session replay records screenshots. Apps that used the default wireframe mode now upload masked screenshots. Custom-drawn views and other content the SDK doesn't recognize, such as maps or video, can be visible unless you mask them. Jetpack Compose screens, which wireframe recorded as empty boxes, now show their content, so check that your consent or privacy notice covers them. Review masking before you upgrade.
  • Compose masking changed. This also applies to apps that already set screenshot = true. Modifier.postHogMask() and Modifier.postHogUnmask() apply only to the element and its children, not to siblings merged into the same clickable row. Text that draws past its layout box is masked in full. Nodes using Modifier.clearAndSetSemantics are masked while text or image masking is on, so use Modifier.postHogUnmask() to show them.
  • $locale is the device language. It's now the first language in the device settings, as a full language tag such as zh-Hant-TW, instead of Locale.getDefault(), which your app can change. Hebrew, Indonesian, and Yiddish values on older Android versions change from the legacy codes iw, in, and ji, so update filters that match those. The new $app_language property is the language your app shows, sent on Android 13+ when it can be read. Call PostHog.setAppLanguage("de") to send it on every version.
  • Super properties win over the SDK's values. A registered super property with the same key as one the SDK sets, such as $os_name, now overrides the SDK's value. A registered $session_id overrides the SDK's session ID, which can detach events from their session replay.
  • Some events and values are dropped or replaced. Events with an empty name are dropped, including ones beforeSend renames to "". Deep link query parameters whose name starts with $ are left out of Deep Link Opened. A uuid you set in beforeSend, for example with copy(uuid = …), is replaced with the uuid of the original capture.
  • Events go to capture v1. Analytics events go to /i/v1/analytics/events instead of /batch. If you self-host PostHog or send events through your own proxy, make sure that path is served first. Capture v1 also changes event validation, property precedence, and retries. See the capture v1 upgrade guide.
  • Feature flag payloads must be valid JSON. A malformed, empty, or whitespace-only payload, or one only valid in lenient mode such as unquoted hello, now reads as null instead of a string. A JSON null payload reads as null instead of the string "null". If you store plain text in a payload, change it to valid JSON such as "hello" before you upgrade. The flag's value isn't affected.
  • remoteConfig = false no longer skips /config. Apps that set it now request /config at setup and apply its session replay, surveys, error tracking, and push settings. /flags is then requested only if the project has feature flags, and if it has none, the cached flags are cleared.

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.

Still have questions?

Was this page useful?