This guide shows you how to easily integrate the Coralogix RUM SDK into your native Android apps.

Coralogix Android SDK supports Android 7.0+ (API level 24) and above.

## Features

In addition to capturing errors, including ANRs, this SDK can intercept network calls, send log messages with customized severity levels, report errors, and track your customers' page transitions.

## Installation

1.

Add the [Maven Central Repository](https://central.sonatype.com/artifact/com.coralogix/android-sdk) to your project. Then, add the dependency to your module's `build.gradle`.

```groovy
dependencies {
    implementation 'com.coralogix:android-sdk:2.11.0'
}
```

2.

Sync your project.

Note

If you encounter a dependency that requires Java 8+ APIs, such as enabling core library desugaring to ensure compatibility across Android versions, see [Troubleshooting](#troubleshooting) for next steps.

## Initialization

Initialize the Coralogix SDK with the application context.

In the initialization snippet, set mandatory fields: `applicationName`, `coralogixDomain`, `publicKey`, `environment`.

```kotlin
import com.coralogix.android.sdk.CoralogixRum
import com.coralogix.android.sdk.model.CoralogixDomain
import com.coralogix.android.sdk.model.CoralogixOptions

val config = CoralogixOptions(
    applicationName = "MyApp",
    coralogixDomain = CoralogixDomain.EU2,
    publicKey = "my_public_key",
    environment = "dev"
)

class DemoApplication : Application() {
    override fun onCreate() {
        super.onCreate()
       CoralogixRum.initialize(this, config)
    }

}
```

Refer to the following fields for `CoralogixOptions`.

| Property              | Type                                   | Description                                                                                                                                                                   | Required | Example                                                                                                                                                                                                               |
| --------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `applicationName`     | `String`                               | Name of the application                                                                                                                                                       | Yes      | `"MyApp"`                                                                                                                                                                                                             |
| `coralogixDomain`     | `CoralogixDomain`                      | The region associated with your Coralogix [**domain**](https://coralogix.com/docs/user-guides/account-management/account-settings/coralogix-domain/index.md)                  | Yes      | `EU1, EU2, US1, US2, US3, AP1, AP2, AP3`                                                                                                                                                                              |
| `publicKey`           | `String`                               | Coralogix token, publicly visible `public_key` value                                                                                                                          | Yes      | `"my_public_key"`                                                                                                                                                                                                     |
| `labels`              | `Map<String,String>`                   | An optional set of labels that are added to every span for enrichment purposes                                                                                                | No       | `labels = mapOf("payment" to "visa")`                                                                                                                                                                                 |
| `environment`         | `String`                               | Specify the environment, such as development, staging, or production                                                                                                          | Yes      | `"production"`                                                                                                                                                                                                        |
| `version`             | `String`                               | Version of the application                                                                                                                                                    | No       | `"v.1.0"`                                                                                                                                                                                                             |
| `userContext`         | `UserContext`                          | User context information, such as user ID, name, email, and additional metadata                                                                                               | No       | `UserContext(userId = "123", username = "User", email = "newUserEmail@example.com", metadata = mapOf("role" to "Admin"))`                                                                                             |
| `viewContext`         | `ViewContext`                          | Description of current activity                                                                                                                                               | No       | `"MyActivityName"`                                                                                                                                                                                                    |
| `instrumentations`    | `Map<Instrumentation, Boolean>`        | Map to turn on/off specific instrumentation. Defaults to all true.                                                                                                            | No       | `instrumentations = mapOf( Instrumentation.Network to false)`                                                                                                                                                         |
| `ignoreUrls`          | `List<String>`                         | A list of URLs to ignore for logging and monitoring purposes. Supports strings and regular expressions for matching.                                                          | No       | `ignoreUrls = listOf("https://jsonplaceholder\\.typicode\\.com/.*", ".*\\.svg", ".*\\.ico")`                                                                                                                          |
| `ignoreErrors`        | `List<String>`                         | List of error patterns to be ignored for logging and monitoring. Supports strings and regular expressions for matching.                                                       | No       | `ignoreErrors = listOf("^IllegalArgumentException$", "IOException", "ANR")`                                                                                                                                           |
| `collectIPData`       | `Boolean`                              | Allow the option to send IP address to identify session country. Defaults to `true`.                                                                                          | No       | `true`                                                                                                                                                                                                                |
| `sessionSampleRate`   | `Number`                               | Percentage of overall sessions being tracked. Defaults to 100%.                                                                                                               | No       | `100%`                                                                                                                                                                                                                |
| `traceParentInHeader` | `Boolean`                              | Add trace context propagation in headers across service boundaries. Defaults to `false`.                                                                                      | No       | `true`                                                                                                                                                                                                                |
| `fpsSamplingSeconds`  | `Number`                               | Interval (in seconds) for collecting and logging frame rate data for performance tracking. Defaults to 300 sec.                                                               | No       | `10`                                                                                                                                                                                                                  |
| `beforeSend`          | `lambda function`                      | Enable event access and modification before sending to Coralogix, supporting content modification, and event discarding.                                                      | No       | `beforeSend = { event -> if (event.userContext?.user_email?.endsWith("@example.com", ignoreCase = true) == true) {event.copy(userContext = event.userContext?.copy(user_email = "sensetive-info",),)} else {event}},` |
| `tracesExporter`      | `(CoralogixTraceExporterData) -> Unit` | Optional callback that receives the raw OTLP span payload alongside the standard RUM export, enabling distributed-tracing integration. See [Trace Exporter](#trace-exporter). | No       | `tracesExporter = { data -> /* forward OTLP payload */ }`                                                                                                                                                             |

## Configuration

### Instrumentation

You can enable or disable specific instrumentation features using the `instrumentations` map. By default, all instrumentations are enabled.

**Example**

```text
instrumentations = mapOf(
    Instrumentation.Network to false  // Disables network instrumentation
)
```

`Instrumentation` **enum:**

- **Error** - Monitors error events.

- **Network** - Intercepts network calls and, optionally, propagates trace context in headers across service boundaries.

- **Custom** - Allows developers to define and track custom events, giving insights into specific actions or behaviors in the application that are critical to the business.

- **MobileVitals** – Collects key app performance metrics, including CPU, memory, FPS, cold start, and warm start events. Learn more in [Mobile Vitals](https://coralogix.com/docs/user-guides/rum/product-features/mobile-performance/index.md).

- **Anr** - Detects Application Not Responsive (ANR) events.

- **UserInteraction** – Automatically tracks user interactions. Currently, only click and long click events are supported.

- **Lifecycle** - Captures app lifecycle activity and fragment events that occur during runtime, providing insights into the application's behavior and performance.

  - Activity lifecycle events:

    - **onActivityCreated** - Triggered when the activity is first created, initializing the activity and setting up the UI.
    - **onActivityStarted** - Called when the activity becomes visible to the user, but may not yet be interactive.
    - **onActivityResumed** - Invoked when the activity enters the `resumed` state, making it fully interactive and allowing user input.
    - **onActivityPaused** - Called when the activity is partially obscured, such as when another activity or a dialog appears, but the activity is still partially visible.
    - **onActivityStopped** - Triggered when the activity is no longer visible to the user and enters the `stopped` state.
    - **onActivitySaveInstanceState** - Called to save the current state of the activity (e.g., UI data, user input) so it can be restored if the activity is restarted.
    - **onActivityDestroyed** - Called just before the activity is destroyed, allowing for final cleanup of resources and references.

  - Fragment lifecycle events:

    - **onFragmentAttached** - Called when the fragment is attached to its host activity. This is the point where the fragment is associated with the activity lifecycle.
    - **onFragmentCreated** - Called when the fragment is created. This occurs only once per fragment instance, even if it is attached and detached multiple times.
    - **onFragmentViewCreated** - Called after the fragment’s view is created and fully inflated. At this point, the fragment's UI is ready.
    - **onFragmentStarted** - Triggered when the fragment enters the `started` phase and becomes visible to the user.
    - **onFragmentResumed** - Called when the fragment enters the `resumed` phase, meaning the fragment is now interactive and the user can interact with it.
    - **onFragmentPaused** - Called when the fragment is partially obscured by another UI element (e.g., another activity, dialog box), but still visible.
    - **onFragmentStopped** - Called when the fragment is no longer visible to the user and has entered the `stopped` state.
    - **onFragmentSaveInstanceState** - Called to save the fragment's state (e.g., UI data, input) when the system needs to save its state (during pauses, backgrounding, or configuration changes), so it can be restored later.
    - **onFragmentViewDestroyed** - Called when the fragment’s view is destroyed and is no longer available, typically when the fragment is removed or replaced.
    - **onFragmentDestroyed** - Called when the fragment instance is fully destroyed, releasing any remaining resources.
    - **onFragmentDetached** - Called when the fragment is detached from its host activity, ending the association between the fragment and its host.

### Mobile Vitals

Set which Mobile Vitals you want to track on Android.

By default, all detectors are enabled. You can selectively enable or disable specific detectors (for example, CPU or memory) using the `mobileVitalsOptions` map in your CoralogixOptions configuration.

```kotlin
val config = CoralogixOptions(
    // ...
    mobileVitalsOptions = mapOf(
        MobileVitalType.CpuUsage to true,
        MobileVitalType.MemoryUsage to false   // disables memory detector
    )
)
```

You can configure the following Mobile Vital detectors:

| Detector key                       | Description                          |
| ---------------------------------- | ------------------------------------ |
| `MobileVitalType.CpuUsage`         | CPU utilization and main-thread time |
| `MobileVitalType.MemoryUsage`      | Memory footprint and utilization     |
| `MobileVitalType.Fps`              | Frame rate (FPS)                     |
| `MobileVitalType.ColdStartTime`    | App cold start duration              |
| `MobileVitalType.WarmStartTime`    | App warm start duration              |
| `MobileVitalType.SlowFrozenFrames` | Slow and frozen frame counts         |

Learn more about metric coverage and visualization in [Mobile Vitals](https://coralogix.com/docs/user-guides/rum/product-features/mobile-performance/index.md).

### Ignoring errors and URLs

- **Ignore errors:** Use `ignoreErrors` to exclude errors matching specific criteria. Supports strings and regular expressions.

```text
    "^IllegalArgumentException$",
         "IOException",
         "ANR"
```

- **Ignore URLs:** Use `ignoreUrls` to exclude URLs matching specific patterns from being traced.

```text
"<https://jsonplaceholder>\\\\.typicode\\\\.com/.*",
        ".*\\\\.svg",
        ".*\\\\.ico",
```

### Network interception

To enable RUM to intercept network events, add `CoralogixOkHttpInterceptor` to your network client.

#### OkHttp

```kotlin
val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(CoralogixOkHttpInterceptor())
    .build()

val request = Request.Builder()
    .url("https://api.example.com/data")
    .build()

val response = okHttpClient.newCall(request).execute()
println(response.body?.string())
```

#### Retrofit

```kotlin
val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(CoralogixOkHttpInterceptor())
    .build()

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

interface ApiService {
    @GET("data")
    suspend fun getData(): Response<DataModel>
}

val apiService = retrofit.create(ApiService::class.java)
val response = apiService.getData()
println(response.body())
```

#### Ktor

Note

Only OkHttp engine is supported.

```kotlin
val httpClient = HttpClient(OkHttp) {
    engine {
        preconfigured = OkHttpClient.Builder()
            .addInterceptor(CoralogixOkHttpInterceptor())
            .build()
    }
}

val response = httpClient.get("https://api.example.com/data")
println(response.bodyAsText())
```

#### Glide (image loading)

```kotlin
val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(CoralogixOkHttpInterceptor())
    .build()

val glide = Glide.get(context)
glide.registry.replace(
    GlideUrl::class.java,
    InputStream::class.java,
    OkHttpUrlLoader.Factory(okHttpClient)
)

Glide.with(context)
    .load("https://api.example.com/image.png")
    .into(imageView)
```

### Network capture rules

By default, the SDK captures request URLs, status codes, and timings via `CoralogixOkHttpInterceptor`. Use `networkCaptureConfig` in `CoralogixOptions` to capture specific request and response headers or payloads on a per-URL basis.

```kotlin
val config = CoralogixOptions(
    // ...
    networkCaptureConfig = listOf(
        NetworkCaptureRule(
            urlPattern = "https://api.example.com/.*",
            reqHeaders = listOf("X-Request-Id"),
            resHeaders = listOf("X-Response-Time"),
            collectReqPayload = true,
            collectResPayload = false
        )
    )
)
```

| `NetworkCaptureRule` field | Description                                                  |
| -------------------------- | ------------------------------------------------------------ |
| `urlPattern`               | Regex pattern that matches request URLs the rule applies to. |
| `reqHeaders`               | List of request header names to capture.                     |
| `resHeaders`               | List of response header names to capture.                    |
| `collectReqPayload`        | When `true`, capture the request body.                       |
| `collectResPayload`        | When `true`, capture the response body.                      |

### Trace exporter

Forward span data to your own collector or backend by setting a trace exporter callback. The callback receives each span batch the SDK produces. Spans continue to flow to Coralogix when this callback is set.

```kotlin
val config = CoralogixOptions(
    // ...
    tracesExporter = { spanData ->
        forwardToCustomCollector(spanData)
    }
)
```

### Modify events with beforeSend

Use `beforeSend` to inspect, transform, or discard events before they reach Coralogix.

```kotlin
val config = CoralogixOptions(
    // ...
    beforeSend = { event ->
        if (event.userContext?.email?.endsWith("@coralogix.com", ignoreCase = true) == true) {
            event.copy(userContext = event.userContext?.copy(email = "redacted"))
        } else {
            event
        }
    }
)
```

## Custom Spans

Use Custom Spans to instrument business-critical operations in your Android app. Spans appear in Coralogix as standalone records or grouped under a parent global span. Custom Spans require SDK version 2.11.0 or above.

### Get the tracer

Acquire a tracer from `CoralogixRum`. Optionally scope which auto-instruments are ignored within the span context:

```kotlin
val tracer = CoralogixRum.getCustomTracer(
    listOf(CoralogixIgnoredInstrument.NETWORK_REQUESTS)
)
```

### Start a global span

A global span is a top-level operation:

```kotlin
val global = tracer.startGlobalSpan(
    name = "checkout-flow",
    labels = mapOf("cartSize" to 3, "currency" to "USD")
)
```

### Add child spans

Within a global span's context, create child spans for sub-operations:

```kotlin
val child = global.startCustomSpan("fetch-prices")
child.setAttribute("endpoint", "/api/v1/prices")
// ... do work ...
child.endSpan()

global.endSpan()
```

## Integration functions

This section lists public functions used to interact with the Coralogix RUM SDK.

### Set user context

Provide user context dynamically as user metadata becomes available.

**Example**

```kotlin
CoralogixRum.setUserContext(
    userContext = UserContext(
        userId = "123",
        username = "User User",
        email = "user@example.com",
        metadata = mapOf("key" to "value")
    )
)
```

### Set labels

Update labels dynamically during runtime.

**Example**

```kotlin
CoralogixRum.setLabels(
    labels = mapOf(
        "environment" to "production",
        "version" to "1.0.2"
    )
)
```

### Initiate custom measurements

Initiate a custom measurement to send numeric data to Coralogix for precise monitoring and analysis.

**Example**

```kotlin
CoralogixRum.sendCustomMeasurement("my-measurement", 1000)
```

### Set view context

When using the SDK, the `ViewContext` will be set to the activity/fragment name by default. Manually update as necessary.

**Example**

```kotlin
CoralogixRum.setViewContext(
    viewName = "CustomViewName"
)
```

### Log messages

Send log messages with customized severity levels.

**Example**

```kotlin
CoralogixRum.log(
    CoralogixLogSeverity.Error,
    "Custom log message error"
)
```

`CoralogixLogSeverity` defines severity levels for logs in the Coralogix system.

| Case       | Raw Value | Severity Level |
| ---------- | --------- | -------------- |
| `Debug`    | 1         | Debug          |
| `Verbose`  | 2         | Verbose        |
| `Info`     | 3         | Informational  |
| `Warn`     | 4         | Warning        |
| `Error`    | 5         | Error          |
| `Critical` | 6         | Critical       |

### Report errors

Report errors appear in the Coralogix platform with level 5 severity.

**Example**

```kotlin
try {
    // code that might throw an error
} catch (t: Throwable) {
    CoralogixRum.reportError(t)
}
```

### Custom spans

Instrument your own code with arbitrary OpenTelemetry spans that appear in the Coralogix RUM trace view. While a global span is active, all auto-instrumented spans (network, error, user-interaction) inherit its `traceId` and carry `parentSpanId`, so they appear as children in the same trace.

Note

`getCustomTracer()` requires `traceParentInHeader` to be enabled in `CoralogixOptions`. The tracer can only be obtained once per session.

**Example**

```kotlin
val tracer = CoralogixRum.getCustomTracer() ?: return

val globalSpan = tracer.startGlobalSpan(
    name = "checkout-flow",
    labels = mapOf("cart.item_count" to 3)
) ?: return

val childSpan = globalSpan.startCustomSpan(name = "payment-step")
childSpan.setAttribute("payment.method", "credit_card")

// ... do work ...

childSpan.endSpan()
globalSpan.endSpan()
```

#### Opt out auto-instrumented spans

To exclude specific auto-instrumented events from the active global span, pass `CoralogixIgnoredInstrument` values when acquiring the tracer.

```kotlin
val tracer = CoralogixRum.getCustomTracer(
    ignoredInstruments = setOf(CoralogixIgnoredInstrument.NETWORK_REQUESTS)
)
```

Network requests are then captured as standalone RUM events without a `parentSpanId`.

For details about prerequisites, use cases, and limitations, see [Custom Spans](https://coralogix.com/docs/user-guides/rum/sdk-features/custom-spans/index.md).

### Trace Exporter

Set the `tracesExporter` callback in `CoralogixOptions` to receive each OTel span as a raw OTLP payload alongside the normal RUM export. Use this to forward spans to your own distributed-tracing pipeline without running a separate OpenTelemetry collector.

```kotlin
val options = CoralogixOptions(
    // ...
    tracesExporter = { data ->
        // data is a CoralogixTraceExporterData OTLP payload
        // forward to your backend or OTLP-compatible endpoint
    }
)
```

For payload format and forwarding considerations, see [Trace Exporter](https://coralogix.com/docs/user-guides/rum/sdk-features/trace-exporter/index.md).

## Troubleshooting

If you encounter a dependency that requires Java 8+ APIs, such as enabling core library desugaring to ensure compatibility across Android versions, do the following:

1.

Update `compileOptions` by adding the following to your `build.gradle` file.

```groovy
android {
    compileOptions {

        **isCoreLibraryDesugaringEnabled = true**
    }

}
```

2.

Add Desugaring Dependency by including the library in your dependencies.

```groovy
dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.0.4")
}
```

This enables modern Java features on older Android versions.
