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 module to your build.gradle:

Terminal
dependencies {
implementation 'com.posthog.android:posthog:1.+'
}

Configuration

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

Java
public class SampleApp extends Application {
private static final String POSTHOG_API_KEY = "<ph_project_api_key>";
private static final String POSTHOG_HOST = "<ph_instance_address>";
@Override
public void onCreate() {
// Create a PostHog client with the given context, API key and host.
PostHog posthog = new PostHog.Builder(this, POSTHOG_API_KEY, POSTHOG_HOST)
.captureApplicationLifecycleEvents() // Record certain application events automatically!
.recordScreenViews() // Record screen views automatically!
.build();
// Set the initialized instance as a globally accessible instance.
PostHog.setSingletonInstance(posthog);
// Now anytime you call PostHog.with, the custom instance will be returned.
PostHog posthog = PostHog.with(this);
}
}

Capturing events

You can send custom events using capture:

Java
PostHog.with(this)
.capture("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:

Java
PostHog.with(this)
.capture("User signed up", new Properties()
.putValue("login_type", "email")
.putValue("is_free_trial", true));

Capturing screen views

With recordScreenViews(), 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 name. You may also pass in an optional properties object.

Java
PostHog.with(this)
.screen("Dashboard", new Properties()
.putValue("background", "blue")
.putValue("hero", "superhog"));

Identify

We highly recommend reading our section on Identifying users to better understand how to correctly use this method.

When you start tracking events with PostHog, each user gets an anonymous ID that is used to identify them in the system. In order to link this anonymous user with someone from your database, use the identify call.

Identify lets you add metadata to your users so you can easily identify who they are in PostHog, as well as do things like segment users by these properties.

An identify call requires:

  • distinctId which uniquely identifies your user in your database
  • userProperties with a dictionary of key:value pairs
Java
PostHog.with(this)
.identify(distinctID, new Properties()
.putValue("name", "My Name")
.putValue("email", "user@posthog.com"));

The most obvious place to make this call is whenever a user signs up, or when they update their information.

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 $set and $set_once.

$set

Example

Java
// import java.util.HashMap;
HashMap<String, Object> userProps = new HashMap<String, Object>();
userProps.put("string", "value1");
userProps.put("integer", 2);
PostHog.with(this)
.capture("Button B Clicked", new Properties()
.putValue("color", "blue")
.putValue("$set", userProps));

Usage

When capturing an event, you can pass a property called $set 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.

$set_once

Example

Java
// import java.util.HashMap;
HashMap<String, Object> userProps = new HashMap<String, Object>();
userProps.put("string", "value1");
userProps.put("integer", 2);
PostHog.with(this)
.capture("Button B Clicked", new Properties()
.putValue("color", "blue")
.putValue("$set_once", userProps));

Usage

$set_once works just like $set, 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.

Java
PostHog posthog = new PostHog.Builder(this, POSTHOG_API_KEY, POSTHOG_HOST)
.flushQueueSize(20)
.flushInterval(30, TimeUnit.SECONDS)
.build();

You can also manually flush the queue:

Java
PostHog.with(this)
.flush();

Reset

To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out.

Java
PostHog.with(this)
.reset();

Feature Flags

PostHog's feature flags enable you to safely deploy and roll back new features.

Boolean feature flags

Java
if (PostHog.with(this).isFeatureEnabled("flag-key") ) {
// do something
}

Multivariate feature flags

Java
if (PostHog.with(this).getFeatureFlag("flag-key") == "variant-key") { // replace 'variant-key' with the key of your variant
// 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 PostHog.with(this).reloadFeatureFlags().

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:

Android
if (PostHog.with(this).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
Java
PostHog.with(this).group("company", "company_id_in_your_db") // organization is the group type, company_id_in_your_db is the group ID
  • Associate the events for this session with a group AND update the properties of that group
Java
PostHog.with(this).group("company", "company_id_in_your_db", new Properties().putValue("name", "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:

Java
PostHog posthog = new PostHog.Builder(this, POSTHOG_API_KEY, POSTHOG_HOST)
// Record certain application events automatically! (off/false by default)
.captureApplicationLifecycleEvents()
// Record screen views automatically! (off/false by default)
.recordScreenViews()
// Capture deep links as part of the screen call. (off by default)
.captureDeepLinks()
// Maximum number of events to keep in queue before flushing (20)
.flushQueueSize(int flushQueueSize)
// Max delay before flushing the queue (30 seconds)
.flushInterval(long flushInterval, TimeUnit timeUnit)
// Enable or disable collection of ANDROID_ID (true)
.collectDeviceId(boolean collect)
.build();

Thank you

This library is largely based on the analytics-android package.

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