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

# SDK Integration

> Quickly integrate Android RUM SDK for real-time monitoring of app performance, errors, and user behavior

<Info>
  Flashduty Android RUM SDK supports **Android 6.0 (API level 23)** and above.
  By integrating the SDK, you can monitor your Android app's performance,
  errors, and user behavior in real-time.
</Info>

<Note>
  **About Dependencies and Package Names**

  Flashduty Android SDK is fully compatible with the Datadog open-source protocol. In `build.gradle`, use `cloud.flashcat` group for dependencies, but in Kotlin/Java code, import classes from the `com.datadog.android` package. You can seamlessly leverage Datadog ecosystem documentation, examples, and best practices while enjoying Flashduty platform services.
</Note>

## Integration Steps

<Steps>
  <Step title="Add SDK Dependencies">
    Add SDK dependencies in your app module's `build.gradle` file:

    ```groovy build.gradle theme={null}
    dependencies {
        implementation "cloud.flashcat:dd-sdk-android-core:<latest-version>"
        implementation "cloud.flashcat:dd-sdk-android-rum:<latest-version>"

        // Required: the SDK relies on Gson and OkHttp at runtime; your app must provide them.
        implementation "com.google.code.gson:gson:2.8.9"
        implementation "com.squareup.okhttp3:okhttp:4.9.0"

        // Optional: add WorkManager if you need background upload scheduling.
        implementation "androidx.work:work-runtime:<workmanager-version>"
    }
    ```

    <Tip>
      Check the [SDK Release Page](https://central.sonatype.com/namespace/cloud.flashcat) for the latest version. Replace `<latest-version>` with the actual version number (e.g., `0.4.1`).
    </Tip>

    <Warning>
      **Gson and OkHttp must be declared explicitly by your app.** The SDK detects them by reflection at startup, but they are `compileOnly` inside the SDK and are not exposed transitively to your project. If they are missing, `Datadog.initialize(...)` throws a `missing dependencies` error and crashes the app on launch — even without obfuscation. If your app already includes Gson / OkHttp, reuse them; you don't need to add them again.
    </Warning>

    <Note>
      WorkManager is also a `compileOnly` dependency, but it is optional. If WorkManager is missing, the SDK logs a warning and disables background upload scheduling; foreground batch uploads continue to work. Add `androidx.work:work-runtime` explicitly when you want the SDK to keep scheduling uploads after the app moves to the background.
    </Note>
  </Step>

  <Step title="Get Application Credentials">
    In the Flashduty console's **RUM Application Management** page:

    1. Create or select an Android application
    2. Get the following credentials:
       * **Application ID** - Application unique identifier
       * **Client Token** - Client access token
  </Step>

  <Step title="Initialize SDK">
    Initialize Flashcat SDK in your `Application` class's `onCreate()` method:

    ```kotlin Application.kt theme={null}
    import com.datadog.android.Datadog
    import com.datadog.android.core.configuration.Configuration
    import com.datadog.android.privacy.TrackingConsent

    class SampleApplication : Application() {
        override fun onCreate() {
            super.onCreate()

            val clientToken = "<CLIENT_TOKEN>"
            val environmentName = "<ENV_NAME>"
            val appVariantName = "<APP_VARIANT_NAME>"

            val configuration = Configuration.Builder(
                clientToken = clientToken,
                env = environmentName,
                variant = appVariantName
            ).build()

            Datadog.initialize(this, configuration, TrackingConsent.GRANTED)
        }
    }
    ```

    <Note>
      **Parameter Description:**

      * `environmentName` - Environment name (e.g., production, staging)
      * `appVariantName` - App variant name, used to distinguish data from different build versions
      * For more configuration options, see [Advanced Configuration](/en/rum/sdk/android/advanced-config)
    </Note>
  </Step>

  <Step title="Enable RUM Features">
    Configure and enable Android SDK's RUM features:

    ```kotlin Application.kt theme={null}
    import com.datadog.android.rum.Rum
    import com.datadog.android.rum.RumConfiguration
    import com.datadog.android.rum.tracking.ActivityViewTrackingStrategy

    val rumConfig = RumConfiguration.Builder(applicationId)
        .trackUserInteractions()
        .trackLongTasks(durationThreshold)
        .useViewTrackingStrategy(ActivityViewTrackingStrategy(true))
        .build()

    Rum.enable(rumConfig)
    ```

    <Check>
      The SDK will automatically start collecting the following data:

      * User interaction events
      * Long task monitoring
      * Activity view tracking
    </Check>
  </Step>

  <Step title="Configure Network Tracking (Optional)">
    Configure network interceptors to track HTTP requests and responses:

    ### Enable distributed Trace tracking

    <Info>
      If you only need request URL, method, status code, and error details in RUM,
      configuring the OkHttp interceptor is enough. To correlate mobile requests
      with backend traces, also add the Trace module and enable `Trace.enable(...)`.
    </Info>

    **Add OkHttp dependency:**

    ```groovy build.gradle theme={null}
    dependencies {
        implementation "cloud.flashcat:dd-sdk-android-okhttp:<latest-version>"
        implementation "cloud.flashcat:dd-sdk-android-trace:<latest-version>"
    }
    ```

    <Tip>
      Check the [SDK Release
      Page](https://central.sonatype.com/namespace/cloud.flashcat) for the latest
      version.
    </Tip>

    `dd-sdk-android-okhttp` records OkHttp requests as RUM Resources. `dd-sdk-android-trace` enables the Trace feature, creates spans, and injects trace headers into first-party requests. Dependencies use the `cloud.flashcat` group, while Kotlin/Java imports still use the `com.datadog.android.*` package.

    **Enable Trace:**

    Enable Trace after `Datadog.initialize(...)` and before sending network requests:

    ```kotlin Application.kt theme={null}
    import com.datadog.android.trace.DatadogTracing
    import com.datadog.android.trace.GlobalDatadogTracer
    import com.datadog.android.trace.Trace
    import com.datadog.android.trace.TraceConfiguration

    Trace.enable(
        TraceConfiguration.Builder().build()
    )

    GlobalDatadogTracer.registerIfAbsent(
        DatadogTracing.newTracerBuilder()
            .withServiceName("<SERVICE_NAME>")
            .build()
    )
    ```

    <Note>
      `Trace.enable(...)` is required to enable the Trace feature. `GlobalDatadogTracer`
      registers a global tracer so OkHttp, coroutine integrations, and manual spans
      can share the same trace configuration. If only OkHttp automatic tracking is
      used, the SDK can create a local tracer when no global tracer is registered,
      but explicit registration is recommended so you can set the `service` name and
      simplify troubleshooting.
    </Note>

    **Configure interceptor:**

    ```kotlin theme={null}
    import com.datadog.android.okhttp.DatadogInterceptor
    import com.datadog.android.trace.TracingHeaderType

    val tracedHostsWithHeaderType = mapOf(
        "example.com" to setOf(
            TracingHeaderType.DATADOG, // datadog protocol
            TracingHeaderType.TRACECONTEXT // w3c standard protocol
        ),
        "api.example.com" to setOf(
            TracingHeaderType.DATADOG,
            TracingHeaderType.TRACECONTEXT
        )
    )

    val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
        .build()
    ```

    <Check>
      With `DatadogInterceptor`, every request handled by OkHttpClient is
      automatically recorded as a RUM Resource when it targets a first-party host.
      When sampled, the SDK also injects trace headers such as `x-datadog-*` and
      `traceparent` / `tracestate` to correlate the request with backend traces.
    </Check>

    <Note>
      * Hosts must be host names only, without `http://`, `https://`, or path. Configuring `example.com` also matches subdomains such as `api.example.com`.
      * Only network requests initiated while a view is active are tracked. To track requests when the app is in background, see [Track Background Events](#track-background-events).
      * If using multiple interceptors, add `DatadogInterceptor` as the first interceptor. Later interceptors that rebuild the `Request` must preserve existing headers.
    </Note>

    **Track Network Redirects or Retries:**

    To monitor network redirects or retries, use `DatadogInterceptor` as a network interceptor:

    ```kotlin theme={null}
    val okHttpClient = OkHttpClient.Builder()
        .addNetworkInterceptor(DatadogInterceptor.Builder(tracedHostsWithHeaderType).build())
        .build()
    ```

    <Tip>
      You can also add an `EventListener` to `OkHttpClient` to automatically track
      resource timing for third-party providers and network requests.
    </Tip>

    **Filter Specific Errors:**

    To filter specific errors reported by `DatadogInterceptor`, configure a custom `EventMapper` in `RumConfiguration`:

    ```kotlin theme={null}
    val rumConfig = RumConfiguration.Builder(applicationId)
        .setErrorEventMapper { errorEvent ->
            if (errorEvent.shouldBeDiscarded()) {
                null
            } else {
                errorEvent
            }
        }
        .build()
    ```
  </Step>
</Steps>

## Advanced Configuration

### Track Background Events

You can track events when the app is running in the background (e.g., crashes and network requests):

```kotlin theme={null}
val rumConfig = RumConfiguration.Builder(applicationId)
    .trackBackgroundEvents(true)
    .build()
```

<Warning>
  Tracking background events may generate additional sessions, affecting
  billing. If you have questions, please contact Flashcat support team.
</Warning>

### Offline Data Handling

The Android SDK ensures data availability when the user's device is offline:

<Check>
  **Data Persistence Mechanism:** - Events are stored locally in batches when
  network signal is weak or device battery is low - Automatically uploaded when
  network recovers, ensuring no data loss - Old data is automatically cleaned up
  to avoid excessive disk usage
</Check>

<Note>
  Even if users use the app while offline, data is retained and uploaded when
  network recovers, ensuring no monitoring data is lost.
</Note>

### Track Local Resource Access

You can track access to assets and raw resources:

<Tabs>
  <Tab title="Assets Resources">
    ```kotlin theme={null}
    val inputStream = context.getAssetAsRumResource(fileName)
    ```
  </Tab>

  <Tab title="Raw Resources">
    ```kotlin theme={null}
    val inputStream = context.getRawResAsRumResource(id)
    ```
  </Tab>
</Tabs>

## WebView Integration

If your Android app contains WebViews, you can enable WebView tracking to monitor web content performance and errors.

<Steps>
  <Step title="Add WebView Dependency">
    ```groovy build.gradle theme={null}
    dependencies {
        implementation "cloud.flashcat:dd-sdk-android-webview:<latest-version>"
    }
    ```

    <Tip>
      Check the [SDK Release Page](https://central.sonatype.com/namespace/cloud.flashcat) for the latest version.
    </Tip>
  </Step>

  <Step title="Enable WebView Tracking">
    Enable WebView tracking in your Activity or Fragment:

    ```kotlin theme={null}
    import com.datadog.android.webview.WebViewTracking

    // Enable tracking for specified WebView
    WebViewTracking.enable(webView, listOf("example.com", "*.example.com"))
    ```

    <Note>
      **Parameter Description:**

      * `webView` - WebView instance to track
      * `allowedHosts` - List of domains to track, supports wildcards (e.g., `*.example.com`)
    </Note>
  </Step>
</Steps>

<Check>
  Web pages in WebView can now be correlated with native app RUM data.
</Check>

## Verify Integration

After integration, verify that the integration is successful:

<Steps>
  <Step title="Access Console">
    Log in to Flashduty console, go to the corresponding RUM application, and check if data is being reported.
  </Step>

  <Step title="Trigger Test Events">
    Perform the following actions in the app to verify data collection: - Open
    different pages in the app to verify page view events - Perform user actions
    (clicks, swipes, etc.) to verify interaction events - Trigger network requests
    to verify resource loading events
  </Step>

  <Step title="Check Logs">
    Check Logcat for network requests to the data reporting endpoint.

    <Check>
      If you see data reporting requests and data appears in the console, the integration is successful!
    </Check>
  </Step>
</Steps>

## ProGuard Configuration

If your app has code obfuscation enabled (ProGuard/R8), add the following rules to your `proguard-rules.pro` file:

```proguard proguard-rules.pro theme={null}
# Flashduty SDK (Datadog compatible)
-keep class com.datadog.android.** { *; }
-dontwarn com.datadog.android.**
```

<Note>
  Since **0.4.1**, the SDK ships its own obfuscation rules through AAR consumer rules. These rules keep `SourceFile`, `LineNumberTable`, the SDK's shaded dependencies, and the Gson / OkHttp classes checked by reflection during initialization. You do **not** need to add Gson / OkHttp keep rules for the SDK yourself. The rule above only keeps the SDK's public classes. If you serialize your own models with Gson, you still need keep rules for **your own** model classes, as usual with Gson.
</Note>

## Next Steps

<CardGroup cols={2}>
  <Card title="Advanced Configuration" icon="sliders" href="/en/rum/sdk/android/advanced-config">
    Configure advanced SDK features like custom sampling, user identification, global context, etc.
  </Card>

  <Card title="Data Collection" icon="database" href="/en/rum/sdk/android/data-collection">
    Learn about data types and data structures collected by the SDK
  </Card>

  <Card title="Insights" icon="chart-line" href="/en/rum/analytics/native">
    View and analyze app performance, errors, and user behavior data
  </Card>

  <Card title="Error Tracking" icon="bug" href="/en/rum/error-tracking/overview">
    Configure crash reporting and error tracking features
  </Card>
</CardGroup>
