> ## Documentation Index
> Fetch the complete documentation index at: https://docs.userpilot.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Android SDK

> Install and configure the Userpilot Android SDK

Install and initialize the Userpilot Android SDK, identify users, track screens and events, and configure optional settings.

The Userpilot Android SDK enables you to capture user insights and deliver personalized in-app experiences in real time. With a one-time setup, you can immediately begin leveraging Userpilot's analytics and engagement features to understand user behavior and guide their journeys in-app.

***

## Getting Started

Your application's `build.gradle` must have a `compileSdk` of 35+ and `minSdk` of 23+, and use Android Gradle Plugin (AGP) 8.1+.

```kotlin theme={null}
android {
    compileSdk 35

    defaultConfig {
        minSdk 23
    }
}
```

Due to the SDK's usage of Jetpack Compose, it is required to either:

1. Apply the `kotlin-android` plugin in your app's `build.gradle` file.

```kotlin theme={null}
plugins {  
  id 'com.android.application' 
  id 'kotlin-android' 
}
```

2. **Or** update to Android Gradle Plugin 8.4.0+.

> [*Related Google issue*](https://issuetracker.google.com/issues/328687152) regarding usage of Jetpack Compose dependency versions 1.6+.

## Installing the Library

The library is distributed through Maven Central. Add the Userpilot module to your `build.gradle` as a dependency and replace `<latest_version>` with the [latest release version](https://central.sonatype.com/artifact/com.userpilot/userpilot-android). Release notes are available [here](./mobile-android-release-notes).

```kotlin theme={null}
repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.userpilot:userpilot-android:<latest_version>'
}
```

Once synced, the Userpilot SDK is available to import throughout your application.

***

## Initialize the SDK

Initialize Userpilot once in your Application class to ensure the SDK is ready as soon as your app starts. Replace `<APP_TOKEN>` with your Application Token from the [Environments Page](https://run.userpilot.io/environment).

<CodeGroup>
  ```kotlin Kotlin theme={null}
  class YourApplication : Application() {
      lateinit var userpilot: Userpilot

      override fun onCreate() {
          super.onCreate()
          userpilot = Userpilot(this, "<APP_TOKEN>") {
              loggingEnabled = true
  		}
      }
  }
  ```

  ```java Java theme={null}
  public class YourApplication extends Application {
      private Userpilot userpilot;

      @Override
      public void onCreate() {
          super.onCreate();
          userpilot = UserpilotKt.Userpilot(application, "<APP_TOKEN>", config -> {
              config.setLoggingEnabled(true);
              return Unit.INSTANCE;
          });
      }
  }
  ```
</CodeGroup>

#### Note for Apps Using AndroidX Startup

If your application also uses `androidx.startup.InitializationProvider`, you **should not** set `tools:node="ignore"` on this provider to disable it. Doing so will **prevent the Userpilot SDK from being initialized correctly.**

Instead, make sure to **merge** the provider declarations using: `tools:node="merge"`

This ensures that your custom initializers and the Userpilot initializer both get registered properly.

## Identify Users (Required)

Identify unique users and companies (groups of users) alongside their properties. Once identified, all subsequent tracked events and screens will be attributed to that user.

<Warning>
  **Important**

  It’s crucial to call the Userpilot identify function; without it, Userpilot won’t be able to recognize your users, and mobile content won’t be displayed to them.
</Warning>

**Recommended Usage:**

* **On user authentication (login):** Immediately call `identify` when a user signs in to establish their identity for all future events.
* **On app launch for authenticated users:** If the user has a valid authenticated session, call `identify` at app launch.
* **Upon property updates:** Whenever user or company properties change.

<CodeGroup>
  ```kotlin Kotlin theme={null}
  userpilot.identify(
      userId = "<USER_ID>",
      properties = mapOf("name" to "John Doe", "email" to "user@example.com", "created_at" to "2019-10-17", "role" to "Admin"),
      company = mapOf("id" to "<COMPANY_ID>", "name" to "Acme Labs", "created_at" to "2019-10-17", "plan" to "Free")
  )
  ```

  ```java Java theme={null}
  Map<String, Object> properties = new HashMap<>();
  properties.put("name", "John Doe");
  properties.put("email", "user@example.com");
  properties.put("created_at", "2019-10-17");
  properties.put("role", "Admin");

  Map<String, Object> company = new HashMap<>();
  company.put("id", "<COMPANY_ID>");
  company.put("name", "Acme Labs");
  company.put("created_at", "2019-10-17");
  company.put("plan", "Free");

  userpilot.identify("<USER_ID>", properties, company);
  ```
</CodeGroup>

**Properties Guidelines**

* The `id` key is required in company properties to identify a unique company.
* Userpilot supports String, Numeric, and Date types.
* Send date values in ISO8601 format.
* If you plan to use Userpilot's localization features, pass the user property `locale_code` with a value that adheres to ISO 639-1 format.
* Userpilot's reserved properties have pre-determined types and improve the profiles interface in the dashboard:
  * Use key `email` to pass the user's email.
  * Use key `name` to pass the user's or company's name.
  * Use key `created_at` to pass the user's or company's signup date.

<Tip>
  **Notes**

  * Make sure your User ID source is consistent across all platform installations (Web, Android, and iOS).
  * While properties are optional, they are essential for Userpilot's segmentation capabilities. We encourage you to define properties with the people responsible for Userpilot integration.
</Tip>

## Track Screens (Required)

Tracking screens is crucial for unlocking Userpilot’s core engagement and analytics capabilities. Screen views are used to trigger eligible in-app experiences, improve targeting, and provide context for analytics by associating subsequent events with the currently active screen.

<Tabs>
  <Tab title="Auto Capture">
    Userpilot SDK supports automatic screen tracking for Android applications, allowing screen views to be captured without manually sending screen events.

    When Auto Capture is enabled, the SDK automatically detects and tracks screens across your app lifecycle.

    ```kotlin Kotlin theme={null}
    val userpilot = Userpilot(context, "<APP_TOKEN>") {
        enableScreenAutoCapture = true
    }
    ```

    <Tip>
      **Note**

      Auto Capture automatically tracks screen views and ignores manually sent `screen` events while enabled.

      If you are migrating from manual screen tracking, please review the migration guide [here](https://docs.userpilot.com/data-events/mobile-screen-tracking/mobile-screen-auto-capture#important).
    </Tip>
  </Tab>

  <Tab title="Manual Tracking">
    If Auto Capture is disabled, you can manually track screens by calling the `screen` API whenever a user navigates to a new screen.

    <CodeGroup>
      ```kotlin Kotlin theme={null}
      userpilot.screen("Profile")
      ```

      ```java Java theme={null}
      userpilot.screen("Profile");
      ```
    </CodeGroup>
  </Tab>
</Tabs>

## Track Events

Log any meaningful action the user performs. Events can be button clicks, form submissions, or any custom activity you want to analyze. Optionally, you can pass metadata with the event to provide specific context.

<CodeGroup>
  ```kotlin Kotlin theme={null}
  userpilot.track("Added to Cart", mapOf("itemId" to "sku_456", "price" to 29.99))
  ```

  ```java Java theme={null}
  Map<String, Object> eventProperties = new HashMap<>();
  eventProperties.put("itemId", "sku_456");
  eventProperties.put("price", 29.99);

  userpilot.track("Added to Cart", eventProperties);
  ```
</CodeGroup>

## Logout

When a user logs out, call `logout()` to clear the current user context. This ensures subsequent events are no longer associated with the previous user.

<CodeGroup>
  ```kotlin Kotlin theme={null}
  userpilot.logout()
  ```

  ```java Java theme={null}
  userpilot.logout();
  ```
</CodeGroup>

## Anonymous Users

If a user is not authenticated, call `anonymous()` to track events without a user ID. This is useful for pre-signup flows or guest user sessions.

<CodeGroup>
  ```kotlin Kotlin theme={null}
  userpilot.anonymous()
  ```

  ```java Java theme={null}
  userpilot.anonymous();
  ```
</CodeGroup>

<Warning>
  Anonymous users are counted towards your Monthly Active Users usage. You should take your account’s MAU limit into consideration before applying this API.
</Warning>

## Experiences

Trigger a specific experience programmatically using its ID. This API allows you to manually initiate an experience within your application.

<CodeGroup>
  ```kotlin Kotlin theme={null}
  userpilot.triggerExperience("<EXPERIENCE_ID>")
  ```

  ```java Java theme={null}
  userpilot.triggerExperience("<EXPERIENCE_ID>");
  ```
</CodeGroup>

End the current active experience:

<CodeGroup>
  ```kotlin Kotlin theme={null}
  userpilot.endExperience()
  ```

  ```java Java theme={null}
  userpilot.endExperience();
  ```
</CodeGroup>

## Configuration (Optional)

| **Parameter**                              | **Type**                    | **Description**                                                                                                                 |
| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| loggingEnabled                             | Boolean                     | Enable or disable logs for the SDK.<br /><br />**Default: false**                                                               |
| enableScreenAutoCapture                    | Boolean                     | Enables automatic screen tracking.<br /><br />**Default: false**                                                                |
| enableInteractionAutoCapture               | Boolean                     | Enables automatic interaction capture.<br /><br />**Default: false**                                                            |
| packageNames                               | List\<String>               | Custom package list for fonts, mostly used when fonts are stored in a different package than your main app (multi-module apps). |
| disableRequestPushNotificationsPermissions | Boolean                     | Disable push notifications permission request by the SDK.<br /><br />**Default: false**                                         |
| useInAppBrowser                            | Boolean                     | Determines whether to open URLs inside CustomTabsIntent or use the system browser.<br /><br />**Default: false**                |
| navigationHandler                          | UserpilotNavigationHandler  | Sets the handler for link navigation. Navigation will be handled by the client app.                                             |
| analyticsListener                          | UserpilotAnalyticsListener  | Sets the listener to be notified about analytics events.                                                                        |
| experienceListener                         | UserpilotExperienceListener | Sets the listener to be notified about experience display and lifecycle events.                                                 |

**Example Usage**

<CodeGroup>
  ```kotlin Kotlin theme={null}
  val userpilot = Userpilot(context, "<APP_TOKEN>") {
              loggingEnabled = true
              enableScreenAutoCapture = true
              enableInteractionAutoCapture = true
              useInAppBrowser = true
              disableRequestPushNotificationsPermissions = true

              navigationHandler = object : UserpilotNavigationHandler {
                  override fun navigateTo(uri: Uri) {

                  }
              }
              analyticsListener = object : UserpilotAnalyticsListener {
                  override fun didTrack(
                      type: UserpilotAnalytic,
                      value: String,
                      properties: Payload,
                  ) {

                  }
              }
              experienceListener = object : UserpilotExperienceListener {
                  override fun onExperienceStateChanged(
                      id: Int,
                      state: UserpilotExperienceState
                  ) {

                  }

                  override fun onExperienceStepStateChanged(
                      id: Int,
                      state: UserpilotExperienceState,
                      experienceId: Int,
                      step: Int,
                      totalSteps: Int,
                  ) {

                  }
              }
          }
  ```

  ```java Java theme={null}
  Userpilot userpilot = UserpilotKt.Userpilot(application, "<APP_TOKEN>", config -> {
              config.setLoggingEnabled(true);
              config.setEnableScreenAutoCapture(true);
              config.setEnableInteractionAutoCapture(true);
              config.setUseInAppBrowser(true);
              config.setDisableRequestPushNotificationsPermissions(true);
              
              Map<String, String> sdkMessages = new HashMap<>();
              sdkMessages.put(UserpilotMessageKeys.PUSH_NOTIFICATION_MESSAGE, "Custom app message");
              config.setSdkMessages(sdkMessages);

              config.setNavigationHandler(new UserpilotNavigationHandler() {
                  @Override
                  public void navigateTo(@NonNull Uri uri) {

                  }
              });

              config.setAnalyticsListener(new UserpilotAnalyticsListener() {
                  @Override
                  public void didTrack(@NonNull UserpilotAnalytic type, @NonNull String value, @Nullable Map<String, ?> properties) {

                  }
              });

              config.setExperienceListener(new UserpilotExperienceListener() {
                  @Override
                  public void onExperienceStepStateChanged(int id, @NonNull UserpilotExperienceState state, int experienceId, int step, int totalSteps) {

                  }

                  @Override
                  public void onExperienceStateChanged(int id, @NonNull UserpilotExperienceState state) {

                  }
              });
              return Unit.INSTANCE;
          });
  ```
</CodeGroup>

<Frame>
  [**For any questions or concerns please reach out to support@userpilot.com**](mailto:support@userpilot.com)
</Frame>
