Android

Last updated:

|Edit this page
Which features are available in this library?
  • Event capture
  • Autocapture
  • User identification
  • Session recording
  • Feature flags
  • Group analytics

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.

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:

Gradle
dependencies {
implementation("com.posthog:posthog-android:3.+")
}

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_api_key>"
// usually 'https://app.posthog.com' or 'https://eu.posthog.com'
const val POSTHOG_HOST = "<ph_instance_address>"
}
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:

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 also include additional information in the event by setting the properties value:

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)

Capturing screen views

With captureScreenViews = true, PostHog will try to record all screen changes automatically.

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"
)
)

Identify

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 every time your app loads for the first time as well as directly 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.

Setting user properties via an event

To set properties on your users via an event, you can leverage the event properties userProperties and userPropertiesSetOnce.

userProperties

Example

Kotlin
import com.posthog.PostHog
PostHog.capture(
event = "button_b_clicked",
properties = mapOf("color" to "blue"),
userProperties = mapOf(
"string" to "value1",
"integer" to 2
)
)

Usage

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.

userPropertiesSetOnce

Example

Kotlin
import com.posthog.PostHog
PostHog.capture(
event = "button_b_clicked",
properties = mapOf("color" to "blue"),
userPropertiesSetOnce = mapOf(
"string" to "value1",
"integer" to 2
)
)

Usage

userPropertiesSetOnce works just like userProperties, except that it will only set the property if the user doesn't already have that property set.

Flush

You can set the number of events in the configuration that should queue before flushing. Setting this to 1 will send events immediately and will use more battery. The default value for this is 20.

You can also configure the flush interval. By default we flush all events after 30 seconds, no matter how many events have been gathered.

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

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

Reset

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.

Boolean feature flags

Kotlin
import com.posthog.PostHog
if (PostHog.isFeatureEnabled("flag-key")) {
// Do something differently for this user
// Optional: fetch the payload
val matchedFlagPayload = PostHog.getFeatureFlagPayload("flag-key")
}

Multivariate feature flags

Kotlin
import com.posthog.PostHog
if (PostHog.getFeatureFlag("flag-key") == "variant-key") { // replace 'variant-key' with the key of your variant
// Do something differently for this user
// Optional: fetch the payload
val matchedFlagPayload = PostHog.getFeatureFlagPayload("flag-key")
}

Ensuring flags are loaded before usage

Every time a user loads a screen, 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:

Kotlin
import com.posthog.PostHog
import com.posthog.android.PostHogAndroidConfig
import com.posthog.PostHogOnFeatureFlags
// During SDK initialization
val config = PostHogAndroidConfig(apiKey).apply {
onFeatureFlags = PostHogOnFeatureFlags {
if (PostHog.isFeatureEnabled("flag-key")) {
// do something
}
}
}
// And/Or manually 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:

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

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.

Groups

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

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

All configuration options

When creating the PostHog client, there are many options you can set:

Kotlin
val config = PostHogAndroidConfig(apiKey = POSTHOG_API_KEY, host = POSTHOG_HOST).apply {
// Capture certain application events automatically. (on/true by default)
captureApplicationLifecycleEvents = true
// Capture screen views automatically. (on/true by default)
captureScreenViews = true // (on/true by default)
// Capture deep links as part of the screen call. (on/true by default)
captureDeepLinks = true
// Maximum number of events to keep in queue before flushing (20 by default)
flushAt = 20
// Number of maximum events in memory and disk, when the maximum is exceed, the oldest event is deleted and the new one takes place. (1000 by default)
maxQueueSize = 1000
// Number of maximum events in a batch call. (50 by default)
maxBatchSize = 50
// Maximum delay before flushing the queue (30 seconds)
flushIntervalSeconds = 30
// Logs the SDK messages into Logcat. (off/false by default)
debug = false
// Prevents capturing any data if enabled. (off/false by default)
optOut = false
// Send a '$feature_flag_called' event when a feature flag is used automatically. (on/true by default)
sendFeatureFlagEvent = true
// Preload feature flags automatically. (on/true by default)
preloadFeatureFlags = true
// Callback that is called when feature flags are loaded (not set by default)
onFeatureFlags = { ... }
// Callback that allows to sanitize the event properties (not set by default)
propertiesSanitizer = { properties -> ... }
}

Questions?

Was this page useful?

Next article

Elixir

This library provides an Elixir HTTP client for PostHog. See the repository for more information. Installation Capturing events Feature flags Feature flags are not supported yet in our Elixir SDK. However, you can integrate them into your project by using the PostHog API . Thanks Thanks to nkezhaya for contributing this library.

Read next article