# Session Replay Android Standalone SDK

This article covers how to install Session Replay for Android with the standalone SDK. If you use a provider other than Amplitude for in-product analytics, choose this option. If your app already uses the Amplitude Android SDK, use the [Session Replay Android SDK Plugin](https://amplitude.com/docs/sdks/session-replay/session-replay-android-plugin) instead.

{% callout type="tip" heading="Report issues" %}
To report issues with Session Replay for Android, go to the [AmplitudeSessionReplay-Android GitHub repository](https://github.com/amplitude/AmplitudeSessionReplay-Android).
{% /callout %}

{% callout type="note" heading="Session Replay and performance" %}

Amplitude built Session Replay to minimize impact on the performance of the Android apps in which it's installed by:

- Asynchronously capturing and processing replay data, to avoid blocking the main user interface thread. The main thread must analyze the view hierarchy, but snapshot capture scheduling and extra processing offloads to the background.
- Using batching and lightweight compression to reduce the number of network connections and bandwidth.
- Optimizing view hierarchy processing. Contact Amplitude if you experience issues with hierarchy processing.

{% /callout %}

## Before you begin

The Session Replay Standalone SDK requires that:

1. Your application is Android-based.
2. You track sessions with a timestamp or a custom string session ID that you can pass to the SDK. Inform the SDK whenever the session identifier changes.
3. You can provide a device ID to the SDK.
4. The `Session ID` and `Device ID` you pass to the Standalone SDK match those sent as event properties to Amplitude.

The Standalone SDK doesn't provide session management capabilities. Your application or a third-party integration must update the SDK with changes to `Session ID` and `Device ID`.

### Supported Android versions

Session replay supports down to Android 5.0 with a minimum SDK of 21 `minSdk = 21`. This should support over 99.6% of global Android devices according to Google's distribution data in Android Studio.

## Quickstart

Add the [latest version](https://central.sonatype.com/artifact/com.amplitude/session-replay-android/versions) of the Session Replay SDK to your project dependencies.

```kotlin
implementation("com.amplitude:session-replay-android:0.27.0")
```

Configure your application code:

1. Create a `val sessionReplay = SessionReplay()` object to start collecting replays. Pass the API key, session identifier, and device identifier.
2. When the session or device identifier changes, pass the new value to Amplitude with `sessionReplay.setSessionId` or `sessionReplay.setDeviceId`. For string session IDs, use `sessionReplay.setCustomSessionId` instead. Refer to [Custom session IDs](#custom-session-ids).
3. Call `sessionReplay.flush` to send session replay data to Amplitude. Always call `flush` before the app exits or moves to the background. For longer sessions, call `flush` often to prevent high memory use (alpha).

```kotlin
import com.amplitude.android.sessionreplay.SessionReplay
import com.example.ThirdPartyAnalytics

// Initialize the standalone session replay SDK
val sessionReplay = SessionReplay(
    apiKey = "api-key",
    context = applicationContext,
    deviceId = "device-id",
    sessionId = Date().time,
    sampleRate = 1.0,
)

// Handle session ID change
// Whenever the session ID changes
ThirdPartyAnalytics.setSessionId(sessionId)
// Update the session ID in session replay
sessionReplay.setSessionId(ThirdPartyAnalytics.getSessionId())

// Handle device ID change
// When the device ID changes
ThirdPartyAnalytics.setDeviceId(deviceId)
//Update the device ID in session replay
sessionReplay.setDeviceId(ThirdPartyAnalytics.getDeviceId())


// Send session replay data to the server
// This should always be called before app exit
sessionReplay.flush()
```

## Configuration

Pass the following configuration options when you initialize the Session Replay SDK.

| Option                               | Type            | Required | Default           | Description                                                                                                                                                                          |
| ------------------------------------ | --------------- | -------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `apiKey`                             | `String`        | Yes      | n/a               | Your Amplitude API key.                                                                                                                                                              |
| `context`                            | `Context`       | Yes      | n/a               | The Android application context.                                                                                                                                                     |
| `deviceId`                           | `String`        | Yes      | n/a               | Identifier for the device running your application.                                                                                                                                  |
| `sessionId`                          | `Long`          | Yes      | n/a               | Identifier for the user's current session, in milliseconds since epoch (Unix timestamp). To use a string session ID instead, pass `-1` and call `setCustomSessionId` after initialization. Refer to [Custom session IDs](#custom-session-ids).                       |
| `sampleRate`                         | `Number`        | No       | `0.0`             | Controls how many sessions Amplitude selects for replay collection. Use a decimal between 0 and 1, for example `0.4`, which selects 40% of sessions over a large number of sessions. |
| `optOut`                             | `Boolean`       | No       | `false`           | Sets permission to collect replays. A value of `true` prevents Amplitude from collecting session replays.                                                                            |
| `logger`                             | `Logger`        | No       | `LogcatLogger`    | Sets a custom logger to emit log messages to a destination. Set to `null` to disable logging.                                                                                        |
| `enableRemoteConfig`                 | `Boolean`       | No       | `true`            | Enables or disables [remote configuration](#remote-configuration) for this instance of Session Replay.                                                                               |
| `serverZone`                         | `ServerZone`    | No       | `ServerZone.US`   | `ServerZone.EU` or `ServerZone.US`. Set this to EU for Amplitude projects created in the EU data center.                                                                             |
| `privacyConfig`                      | `PrivacyConfig` | No       | `PrivacyConfig()` | Privacy settings that control which views are masked. Set the mask level with `PrivacyConfig(maskLevel = MaskLevel.MEDIUM)`. See [Mask level](#mask-level).                          |
| `serverUrl`                          | `String?`       | No       | `null`            | *Advanced.* Explicit server URL, useful for proxy setups.                                                                                                                            |
| `bandwidthLimitBytes`                | `Int?`          | No       | `null`            | *Advanced.* Daily upload limit, in bytes, on metered (for example, cellular) connections.                                                                                            |
| `storageLimitMB`                     | `Int?`          | No       | `null`            | *Advanced.* Local storage limit, in MB.                                                                                                                                              |
| `autoStart`                          | `Boolean`       | No       | `true`            | Starts screen capture automatically when Session Replay initializes.                                                                                                                 |
| `recordLogOptions.logCountThreshold` | `Int`           | No       | `1000`            | Maximum number of logs per session.                                                                                                                                                  |
| `recordLogOptions.maxMessageLength`  | `Int`           | No       | `2000`            | Maximum length of a log message.                                                                                                                                                     |

### Custom session IDs

Session Replay for Android version 0.26.4 and later supports string session IDs, for example UUIDs, through the `setCustomSessionId` method. Use a custom session ID if your project defines sessions with a custom event property instead of a timestamp-based `session_id`.

The constructor accepts only a numeric `sessionId`. To use a string value, pass `-1` as the `sessionId`, then call `setCustomSessionId`. Session Replay doesn't capture until you set a valid session ID.

```kotlin
val sessionReplay = SessionReplay(
    apiKey = API_KEY,
    context = applicationContext,
    deviceId = "device-id",
    sessionId = -1,
    sampleRate = 1.0,
)

// Set a string session ID instead of the numeric sessionId
sessionReplay.setCustomSessionId("ef197fc7-a46f-4e6c-a77f-8d90c17065c0")

// Whenever your custom session changes
sessionReplay.setCustomSessionId(ThirdPartyAnalytics.getCustomSessionId())
```

The numeric `sessionId` and the custom session ID are two views of the same underlying value, which the SDK stores as a string:

- Calling `setSessionId` replaces the current custom session ID with the numeric value. When you use custom session IDs, call `setCustomSessionId` instead of `setSessionId` whenever the session changes.
- When the stored value isn't numeric, `getSessionId` returns `-1`. Call `getCustomSessionId` to read the current value.
- Setting a different value ends the current replay and starts a new one.

For Session Replay to match custom sessions reliably, custom session IDs must follow these constraints:

- The value can't contain `/`. Session Replay uses `/` as a delimiter in the session replay ID, which has the format `<deviceId>/<sessionId>`.
- The value can only contain the characters `a-z A-Z 0-9 _ - . | @ : =`.
- The value must match the session-defining property you send on events to Amplitude. For more information, refer to [Session matching](https://amplitude.com/docs/session-replay/session-matching).

### Remote configuration

Enable remote configuration to set Sample Rate and Masking Level in Amplitude. 

{% callout type="note" heading="Remote configuration and testing" %}
With `enableRemoteConfig` set to `true`, settings you define in Amplitude take precedence over settings you define locally in the SDK. For this reason, while testing your application, you should **disable** remote configuration to ensure you can set `sampleRate` to `1`, and ensure you capture test sessions.

{% /callout %}

### Mask on-screen data

The Session Replay SDK offers three ways to mask user input, text, and other view components.

#### Mask level

Session Replay for Android supports three levels of masking, set through the `privacyConfig` option with `PrivacyConfig(maskLevel = MaskLevel.MEDIUM)`. The default level is `medium`.

Use this option in the Session Replay configuration.

| Mask level | Description |
| ------| -----|
| `light` | Masks password, email, and phone number input fields. In SDK `0.26.2` and later, `light` also masks any field with sensitive autofill hints (credit card number, expiration, and security code; name; username; postal address and code); autofill-hint detection requires Android 8.0 (API 26) or higher. Earlier versions, including the `middleware-session-replay-android` artifact, mask only the input-field types above. |
| `medium` (default) | Everything in `light`, plus all editable text fields (`EditText`). |
| `conservative` | Everything in `medium`, plus all text views (`TextView`). |

#### Privacy tags in layout XML

Use this option in your application's layout XML.

| View              | Description                                                                                                                                                                                                                                                                                 |
|-------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `<EditText>`      | Session Replay masks all text input fields by default. When a users enters text into an input field, Session Replay captures asterisks in place of text. To *unmask* a text input, add the tag `amp-unmask`. For example: `<EditText android:tag="amp-unmask" android:text="Unmask this">`. |
| `<TextView>`      | To mask text within non-input elements, add the tag `amp-mask`. For example, `<TextView android:tag="amp-mask" android:text="Mask this"/>`. When masked, Session Replay captures masked text as a series of asterisks.                                                                      |
| non-text elements | To block a non-text element, add the tag `amp-block`. For example, `<ImageView android:tag="amp-block"/>`. Session Replay replaces blocked elements with a placeholder of the same dimensions.                                                                                              |
| `<WebView>` | To unmask a web view, add the `amp-unmask` tag. For example, `<WebView android:tag="amp-unmask"/>`.                                                                                              |


#### Privacy methods on the Session Replay SDK

Import the `SessionReplay` class, then call one of the methods below from your application's code.

```kotlin
import com.amplitude.android.sessionreplay.SessionReplay
```

| Method               | Description                                                                                                                                                                                                                                                                         |
|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `unmask(view: View)` | To unmask a view manually, call `SessionReplay.unmask(view)` where `view` is a reference to any view that is masked. |
| `mask(view: View)`   | To mask text within non-input views, call `SessionReplay.mask(view)` where `view` is a reference to the any view you want to mask. When masked, Session Replay captures masked text as a series of asterisks.                                                                     |
| `block(view: View)`  | To block a non-text view, call `SessionReplay.block(view)` where `view` is a reference to the View you want to block. Session Replay replaces blocked views with a placeholder of the same dimensions.                                                                             |

### User opt-out

Session Replay provides an opt-out configuration option. Pass `optOut = true` during initialization to prevent Amplitude from collecting session replays. For example:

```kotlin
// Pass a boolean value to indicate a users opt-out status
val sessionReplay = SessionReplay(
    apiKey = API_KEY,
    optOut = true,
    /* other session replay options */
)
```

### EU data residency

Session Replay is available to Amplitude Customers who use the EU data center. Set the `serverZone` configuration option to `EU` during initialization. For example:

```kotlin
// Set serverZone to EU
val sessionReplay = SessionReplay(
    apiKey = API_KEY,
    serverZone = ServerZone.EU,
    /* other session replay options */
)
```

### Sampling rate

By default, Session Replay captures 0% of sessions for replay. Use the `sampleRate` configuration option to set the percentage of total sessions that Session Replay captures. For example:

To set the `sampleRate` consider the monthly quota on your Session Replay plan. For example, if your monthly quota is 2,500,000 sessions, and you average 3,000,000 monthly sessions, your quota is 83% of your average sessions. In this case, to ensure sampling lasts through the month, set `sampleRate` to `.83` or lower.

Keep the following in mind as you consider your sample rate:

- When you reach your monthly session quota, Amplitude stops capturing sessions for replay.
- Session quotas reset on the first of every month.
- Use sample rate to distribute your session quota over the course of a month, rather than using your full quota at the beginning of the month.
- To find the best sample rate, Amplitude recommends that you start low, for example `.01`. If this value doesn't capture enough replays, raise the rate over the course of a few days. For ways to monitor the number of session replays captured, see [View the number of captured sessions](https://amplitude.com/docs/session-replay#view-the-number-of-captured-sessions).
- Replays with [processing errors](https://amplitude.com/docs/session-replay/session-replay-plugin#troubleshooting) don't count toward your monthly quota. Replays with a retention error message have already been counted against the quota, when the session was still in the retention period.

```kotlin
// This configuration samples 1% of all sessions
val sessionReplay = SessionReplay(
    apiKey = API_KEY,
    sampleRate = 0.01,
    /* other session replay options */
)
```

### Disable replay collection

After Session Replay starts, it runs in your app until either:

- The user leaves your app.
- You call `sessionReplay.stop()`.
- You call `sessionReplay.shutdown()` to tear down the instance.

Call `sessionReplay.stop()` before a user navigates to a restricted area of your app to pause replay collection while the user is in that area. Call `sessionReplay.start()` to resume when they return. Both methods act on the same instance.

To tear down Session Replay completely, call `sessionReplay.shutdown()`, then create a new instance to start again.

To capture only specific screens, initialize Session Replay with `autoStart = false` so it doesn't start on launch, then call `start()` and `stop()` as the user enters and leaves those screens:

```kotlin
val sessionReplay = SessionReplay(
    apiKey = API_KEY,
    context = applicationContext,
    deviceId = "device-id",
    sessionId = Date().time,
    autoStart = false,
)

// Start capture when the user enters a screen you want to record
sessionReplay.start()

// Stop capture when the user leaves that screen
sessionReplay.stop()
```

You can also use a feature flag product like Amplitude Experiment to create logic that enables or disables replay collection based on criteria like location. For example, create a feature flag that targets a specific user group, then add the flag to your initialization logic:

```kotlin
import com.amplitude.android.sessionreplay.SessionReplay
import com.example.ThirdPartyAnalytics

val sessionReplay = SessionReplay(
    apiKey = API_KEY,
    deviceId = "device-id",
    sessionId = Date().time,
    sampleRate = 1.0,
    /* other session replay options */
)
```

### WebView and MapView support (Beta)

By default, Session Replay blocks web views and map views in a capture. To enable capture of these components, use the settings described in [Mask on-screen data](#mask-on-screen-data).

Web view session replay injects JavaScript into the rendered page. To enable this, the SDK sets `javaScriptEnabled` to `true` on the unmasked web view.

### Log Recording

{% callout type="note" heading="Availability" %}
Log recording is available in Session Replay Android `0.22.0` and later.
{% /callout %}

Session Replay supports recording logs in Android applications. To enable log recording, send log messages through the `recordLog(level, message, timestamp)` API and configure the limits through `recordLogOptions` parameter while initializing Session Replay.

```kotlin
import com.amplitude.android.plugins.SessionReplayPlugin
import com.amplitude.android.sessionreplay.config.RecordLogLevel
import com.amplitude.android.sessionreplay.config.RecordLogOptions

val sessionReplayPlugin = SessionReplayPlugin(
    recordLogOptions = RecordLogOptions(
        logCountThreshold = 2000,
        maxMessageLength = 4000
    )
)
amplitude.add(sessionReplayPlugin)

sessionReplayPlugin.recordLog(RecordLogLevel.Error, "This is an error log")

// You can also create custom log levels
sessionReplayPlugin.recordLog(RecordLogLevel("debug"), "This is a debug log")
```

Session Replay supports predefined log levels (`Error`, `Warn`, `Log`) and custom log levels. Create custom log levels by passing any string value to `RecordLogLevel(...)`.

If you have implemented a log system, you can make single-point modifications to integrate log recording functionality. See the following examples for more information.

#### Timber

If you use `Timber`, you can integrate it with a custom tree.

```kotlin
import com.amplitude.android.plugins.SessionReplayPlugin
import com.amplitude.android.sessionreplay.config.RecordLogLevel
import timber.log.Timber

class AmplitudeLogRecordTree(private val plugin: SessionReplayPlugin) : Timber.Tree() {
    override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
        val recordLevel = when (priority) {
            android.util.Log.ERROR -> RecordLogLevel.Error
            android.util.Log.WARN -> RecordLogLevel.Warn
            android.util.Log.INFO -> RecordLogLevel.Log
            android.util.Log.DEBUG -> RecordLogLevel("debug")
            android.util.Log.VERBOSE -> RecordLogLevel("verbose")
            else -> return
        }
        plugin.recordLog(recordLevel, message)
    }
}

val sessionReplayPlugin = SessionReplayPlugin()
amplitude.add(sessionReplayPlugin)

Timber.plant(AmplitudeLogRecordTree(sessionReplayPlugin))
```

## Data retention, deletion, and privacy

Session replay uses existing Amplitude tools and APIs to handle privacy and deletion requests.
<!--vale off-->
{% callout type="note" heading="Consent management and Session Replay" %}
While privacy laws and regulations vary across states and countries, certain constants exist, including the requirements to disclose in a privacy notice the categories of personal information you are collecting, the purposes for its use, and the categories of third parties with which personal information is shared. When implementing a session replay tool, you should review your privacy notice to make sure your disclosures remain accurate and complete. And as a best practice, review your notice with legal counsel to make sure it complies with the constantly evolving privacy laws and requirements applicable to your business and personal information data practices.
{% /callout %}


### Retention period

If your Amplitude plan includes Session Replay, Amplitude retains raw replay data for 30 days from the date of ingestion. 

If you purchase extra session volume, Amplitude retains raw replay data for 90 days from the date of ingestion. If you need a more strict policy, contact Amplitude support to set the value to 30 days.

Changes to the retention period impact replays ingested after the change. Sessions captured and ingested before a retention period change retain the previous retention period.

Retention periods are set at the organization level. Replays that are outside of the retention period aren't viewable in Amplitude.

### DSAR API

The Amplitude [DSAR API](https://amplitude.com/docs/apis/analytics/ccpa-dsar) returns metadata about session replays, but not the raw replay data. All events that are part of a session replay include a `[Amplitude] Session Replay ID` event property. This event provides information about the sessions collected for replay for the user, and includes all metadata collected with each event.

```json
{
  "amplitude_id": 123456789,
  "app": 12345,
  "event_time": "2020-02-15 01:00:00.123456",
  "event_type": "first_event",
  "server_upload_time": "2020-02-18 01:00:00.234567",
  "device_id": "your device id",
  "user_properties": { ... }
  "event_properties": {
    "[Amplitude] Session Replay ID": "cb6ade06-cbdf-4e0c-8156-32c2863379d6/1699922971244"
  }
  "session_id": 1699922971244,
}
```

### Data deletion

Session Replay uses Amplitude's [User Privacy API](https://amplitude.com/docs/apis/analytics/user-privacy) to handle deletion requests. Successful deletion requests remove all session replays for the specified user.

When you delete the Amplitude project on which you use Session Replay, Amplitude deletes that replay data.

### Bot filter

Session Replay uses the same [block filter](https://amplitude.com/docs/data/block-bot-traffic) available in the Amplitude app. Session Replay doesn't block traffic based on event or user properties.

## Session Replay storage

If a user opts out tracking in your app, use the `optOut` configuration option to disable replay collection for that user.

- Memory usage grows until you call `flush()` to transfer the session replay data to the server.
- Session data isn't retried on failure to transfer to the Amplitude servers.

## Jetpack Compose Support (Alpha)

Session Replay supports Jetpack Compose for Android applications. This feature is currently in Alpha. To use Jetpack Compose with Session Replay, ensure you use version `0.20.4` or higher of the Session Replay Android SDK or plugin. Masking support for Compose requires `0.21.0` or higher.

## Known limitations

Keep the following limitations in mind as you implement Session Replay:

- Session Replay doesn't stitch together replays from a single user across multiple projects. For example:
  
    - You instrument multiple apps as separate Amplitude projects with Session Replay enabled in each.
    - A known user begins on one app, and then switch to another.
    - Amplitude captures both sessions.
    - The replay for each session is available for view in the corresponding host project.

- The User Sessions chart doesn't show session replays if your organization uses a custom session definition.
- Session Replay can't capture the following Android views:

    - Canvas Views

## Troubleshooting

For more information about individual statuses and errors, see the [Session Replay Ingestion Monitor](https://amplitude.com/docs/session-replay/ingestion-monitor).                                                                                    |


### Captured sessions contain limited information

Session Replay requires that the Android SDK send at least one event that includes Session Replay ID. If you instrument events outside of the Android SDK, Amplitude doesn't tag those events as part of the session replay. This means you can't use tools like Funnel Analysis, Segmentation, or Journeys charts to find session replays. You can find session replays with the User Sessions chart or through User Lookup.

If you use a method other than the Android SDK to instrument your events, consider using the [Session Replay Standalone SDK for Android](https://amplitude.com/docs/session-replay/session-replay-android-standalone/).

### Replay length and session length don't match

In some scenarios, the length of a replay may exceed the time between the `[Amplitude] Start Session` and `[Amplitude] End Session` events. This happens when a user closes the `[Amplitude] End Session` occurs, but before the Android SDK and Session Replay plugin can process it. When the user uses the app again, the SDK and plugin process the event and send it to Amplitude, along with the replay. You can verify this scenario occurs if you see a discrepancy between the `End Session Client Event Time` and the `Client Upload Time`.

### Session replays don't appear in Amplitude

Session replays may not appear in Amplitude due to:

- Lack of connectivity
- Failed to flush recording before exiting the app
- No events triggered through the Android SDK in the current session
- Sampling

#### Lack of connectivity

Ensure your app has access to the internet then try again.

#### No events triggered through the Android SDK in the current session

Session Replay requires that at least one event in the user's session has the `[Amplitude] Session Replay ID` property. If you instrument your events with a method other than the [Android SDK](https://amplitude.com/docs/sdks/analytics/android/android-kotlin-sdk), the Android SDK may send only the default Session Start and Session End events, which don't include this property.

For local testing, you can force a Session Start event to ensure that Session Replay functions.

1. In Amplitude, in the User Lookup Event Stream, you should see a Session Start event that includes the `[Amplitude] Session Replay ID` property. After processing, the Play Session button should appear for that session.

#### Sampling

As mentioned above, the default `sampleRate` for Session Replay is `0`. Update the rate to a higher number. For more information see, [Sampling rate](#sampling-rate).

#### Some sessions don't include the Session Replay ID property

Session replay doesn't require that all events in a session have the `[Amplitude] Session Replay ID` property, only that one event in the session has it. Reasons why `[Amplitude] Session Replay ID`  may not be present in an event include:

- The user may have opted out or may not be part of the sample set given the current `sampleRate`. Increasing the `sampleRate` captures more sessions.
- Amplitude events may still send through your provider, but `getSessionReplayProperties()` doesn't return the `[Amplitude] Session Replay ID` property. This can result from `optOut` and `sampleRate` configuration settings. Check that `optOut` and `sampleRate` are set to include the session.

### Session Replay processing errors

In general, replays should be available within minutes of ingestion. Delays or errors may be the result of one or more of the following:

- Mismatching API keys or Device IDs. This can happen if Session Replay and standard event instrumentation use different API keys or Device IDs.
- Session Replay references the wrong project.
- Short sessions. If a users bounces within a few seconds of initialization, the SDK may not have time to upload replay data.
- Page instrumentation. If Session Replay isn't implemented on all pages a user visits, their session may not capture properly.
- Replays older than the set [retention period](#retention-period) (defaults to 90 days).

### Report an Issue

If you encounter any issues with Session Replay that aren't covered in the troubleshooting guide above, please report them on our [GitHub repository](https://github.com/amplitude/AmplitudeSessionReplay-Android).

When creating an issue, please include:
- A clear description of the problem
- Steps to reproduce the issue
- Expected vs actual behavior
- SDK version you're using
- Any relevant error messages or logs
