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

# Android SDK

> Add Gravity contextual ads to Android apps with the Kotlin SDK.

Use the `ai.trygravity:gravity-sdk` library to request Gravity ads from your Android app and show them with Jetpack Compose or Android Views. This page describes version 1.2.1. For the terms on this page, see [Core concepts](https://docs.trygravity.com/introduction/concepts.md).

## Before you start

* Your app targets Android 7.0 (API 24) or later.
* You have a Gravity API key. Get it from your dashboard under **Settings → Platform Settings**.

> [!WARNING]
>
> Your API key is in the app package, and users can extract it. Use the key only for ad requests and feedback.

## Install

Add the dependency to the `build.gradle.kts` file of your module:

```kotlin theme={null}
dependencies {
    implementation("ai.trygravity:gravity-sdk:1.2.1")
}
```

The SDK manifest declares the `INTERNET` permission, so you do not need to add it. The SDK uses OkHttp and Kotlin Coroutines. The Compose dependencies are `compileOnly`, so your app gets them only if it already uses Compose.

## Quick start

1. Make one `Gravity` instance with a `Context` and your API key. It requests test ads until you set `production = true` at go-live.
2. Call `gravity.getAds(...)` with the conversation messages, the session ID, and the placements. Run it in a coroutine at the same time as your model call.
3. Show the ad with `SpecAd` (Compose) or `GravityAdView` (Views).

```kotlin theme={null}
import ai.trygravity.sdk.Gravity
import ai.trygravity.sdk.models.*

// 1. Make the client one time, for example in your ViewModel or Application
val gravity = Gravity(context, apiKey = "YOUR_API_KEY")

// 2. Request ads at the same time as your model call
val messages = listOf(
    Message("user", "What's the best way to deploy a Postgres DB?"),
    Message("assistant", "Here are some options..."),
)

viewModelScope.launch {
    val adDeferred = async { gravity.getAds(
        messages = messages,
        sessionId = "sess_abc123",
        userId = currentUser.id,
        placements = listOf(Placement.belowResponse("YOUR_PLACEMENT_ID")),
    ) }

    // Stream your model response...
    val result = adDeferred.await()

    // 3. Show the ad
    result.ads.firstOrNull()?.let { ad ->
        // Give the ad to SpecAd, or to your own UI
    }
}
```

## Constructor

```kotlin theme={null}
Gravity(
    context: Context,
    apiKey: String = System.getenv("GRAVITY_API_KEY") ?: "",
    apiUrl: String = "https://server.trygravity.ai/api/v1/ad",
    feedbackUrl: String = "https://platform.trygravity.ai/ad-feedback",
    timeoutSeconds: Long = 4L,
    production: Boolean = false,
    relevancy: Double = 0.2,
    excludedTopics: List<String>? = null,
    readCMPConsent: Boolean = true,
    honorAdTrackingLimit: Boolean = true,
)
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `context` | `Context` | Required | The Android context. The SDK uses it to collect device data. |
| `apiKey` | `String` | The `GRAVITY_API_KEY` environment variable | Your Gravity API key. |
| `timeoutSeconds` | `Long` | `4` | The request timeout in seconds. |
| `production` | `Boolean` | `false` | When `false`, Gravity returns test ads and does not bill. |
| `relevancy` | `Double` | `0.2` | The minimum relevancy, from 0.0 to 1.0. |
| `excludedTopics` | `List<String>?` | `null` | Topics that ads must not match. |
| `readCMPConsent` | `Boolean` | `true` | Read the consent that your IAB consent management platform (CMP) stored (TCF and US Privacy keys, and from version 1.4.0 the GPP keys `IABGPP_HDR_GppString` and `IABGPP_GppSID`), and send it with each request. Privacy signals are required: see [Send privacy signals](https://docs.trygravity.com/ai-platforms/privacy-signals.md). A `consent` value you pass to `getAds()` replaces what the SDK reads. |
| `honorAdTrackingLimit` | `Boolean` | `true` | If the device limits ad tracking, the request asks for contextual-only ads (`consent.gpc = true`). This needs `play-services-ads-identifier` in your app. |

## `getAds()`

```kotlin theme={null}
suspend fun getAds(
    messages: List<Message>,
    sessionId: String,
    userId: String = "anonymous",
    placements: List<Placement>,
    userIP: String? = null,
    hashedIdentity: HashedIdentity? = null,
    extraUserFields: Map<String, String>? = null,
    extraDeviceFields: Map<String, Any>? = null,
    production: Boolean? = null,
    relevancy: Double? = null,
    consent: ConsentSignal? = null,
): AdResult
```

Pass the end user's IP address as `userIP`. The SDK sends it as `device.ip`. The SDK cannot detect the end user's IP address by itself, so pass it when your server knows it.

The SDK collects device data (User-Agent, OS, device model, screen size, time zone, locale, and device type) and sends it with the request. The Device and Geography reports in your dashboard work with no extra code.

`getAds()` never throws. On a failure, it returns `AdResult.EMPTY` (no ads, `status` `0`). `AdResult` has `ads`, `status`, `elapsedMs`, and `error`.

## Model usage

> [!NOTE]
>
> The published SDK doesn't have a model `usage` option. To report model usage, send it in a direct HTTP request to the ad API: see [Report model usage](https://docs.trygravity.com/ai-platforms/request-ads.md#report-model-usage).

Pass a stable `userId`, including for signed-out users. The default `"anonymous"` is excluded from per-user analytics. `extraUserFields` only accepts string values, so it can't carry the nested `user.tags` object.

## Placements

```kotlin theme={null}
// Ready-made placement types. Pass the slug of a placement you created:
// the default ID "main" works only if you registered a placement named "main".
Placement.belowResponse("YOUR_PLACEMENT_ID")           // "below_response"
Placement.inlineResponse("YOUR_PLACEMENT_ID")          // "inline_response"
Placement.aboveResponse("YOUR_PLACEMENT_ID")           // "above_response"

// Other placements
Placement("right_response", "sidebar")
```

## Show ads with Jetpack Compose

```kotlin theme={null}
import ai.trygravity.sdk.views.SpecAd

@Composable
fun ChatScreen(response: String, ads: List<AdResponse>, gravity: Gravity, sessionId: String) {
    Column {
        Text(response)
        ads.firstOrNull()?.let { ad ->
            SpecAd(
                ad = ad,
                gravity = gravity,
                sessionId = sessionId,
            )
        }
    }
}
```

`SpecAd` draws the placement design that Gravity manages, and shows a built-in card when no valid design is available. It records the impression and the click, shows the required ad label and images, and shows feedback buttons.

| Parameter | Type | Description |
| - | - | - |
| `ad` | `AdResponse` | The ad from `getAds()`. |
| `gravity` | `Gravity` | The client instance, for tracking. |
| `sessionId` | `String` | Must be the same value as in the ad request. |
| `modifier` | `Modifier` | The Compose modifier. Default `Modifier`. |
| `theme` | `GravityTheme` | The colors for the ad. Default `GravityTheme()`. |
| `showFeedback` | `Boolean` | Show thumbs-up and thumbs-down buttons under the ad. Default `true`. A tap sends the feedback and hides the buttons. A feedback tap does not count as an ad click. |

`GravityAd` (in `ai.trygravity.sdk.views`) is the built-in Compose card without server-rendered designs. It takes `ad`, `gravity`, `sessionId`, `modifier`, and `showFeedback`.

## Show ads with Android Views

For layouts in XML, use `GravityAdView`. It shows the built-in card, records the impression, and opens `clickUrl` on a tap. It does not show feedback buttons.

```kotlin theme={null}
import ai.trygravity.sdk.views.GravityAdView

val adView = GravityAdView(
    context = this,
    ad = ad,
    sdk = gravity,
    sessionId = sessionId,
)
container.addView(adView)
```

## Custom renderer

If you show ads with your own UI, record the impression and the click yourself:

```kotlin theme={null}
// Impression: call this one time, when the ad becomes visible
gravity.trackImpression(ad)

// Click: opens clickUrl (not url)
gravity.handleClick(context, ad)
```

## Hash PII

To help attribution, send a hashed email and phone. The SDK hashes them on the device, so the raw values do not leave the device.

```kotlin theme={null}
import ai.trygravity.sdk.hashPII

val hashed = hashPII(email = user.email, phone = user.phone)

val result = gravity.getAds(
    messages = messages,
    sessionId = sessionId,
    userId = user.id,
    placements = listOf(Placement.belowResponse("YOUR_PLACEMENT_ID")),
    hashedIdentity = hashed,
)
```

## Ad feedback

Use `sendFeedback()` if you make your own feedback UI. It sends the request in the background and ignores errors.

```kotlin theme={null}
// Thumbs up
gravity.sendFeedback(
    sessionId = sessionId,
    ad = ad,
    sentiment = Gravity.Sentiment.THUMBS_UP,
)

// Thumbs down with reasons
gravity.sendFeedback(
    sessionId = sessionId,
    ad = ad,
    sentiment = Gravity.Sentiment.THUMBS_DOWN,
    reasons = listOf("not_interested", "irrelevant"),
)
```

For the reason values, see [Ad feedback](https://docs.trygravity.com/engine/ad-feedback.md).

## Full example: request ads during the model stream

```kotlin theme={null}
import ai.trygravity.sdk.Gravity
import ai.trygravity.sdk.models.*

class ChatViewModel(application: Application) : AndroidViewModel(application) {
    private val gravity = Gravity(application, apiKey = "YOUR_API_KEY")

    val ads = MutableStateFlow<List<AdResponse>>(emptyList())
    val response = MutableStateFlow("")

    fun send(messages: List<Message>, sessionId: String, userId: String) {
        viewModelScope.launch {
            // Start the ad request
            val adDeferred = async {
                gravity.getAds(
                    messages = messages,
                    sessionId = sessionId,
                    userId = userId,
                    placements = listOf(Placement.belowResponse("YOUR_PLACEMENT_ID")),
                )
            }

            // Stream the model response
            streamLLM(messages).collect { chunk ->
                response.update { it + chunk }
            }

            // Add the ads
            ads.value = adDeferred.await().ads
        }
    }
}
```

## FAQ

> [accordion] Does the ad request block my model response?
>
> No. Use `async` to start `getAds()` at the same time as your model stream. `getAds()` never throws. On a failure, it returns an empty list.

> [accordion] Does the SDK collect the advertising ID (GAID)?
>
> No. The SDK does not send the Google advertising ID. If the user gave consent, you can send it: `extraDeviceFields = mapOf("ifa" to gaid)`.

> [accordion] Which Android versions does the SDK support?
>
> Android 7.0 (API 24) and later.

## Troubleshoot

| Problem | Cause and fix |
| - | - |
| `result.ads` is empty and `status` is `0` | The request got no response, for example because of a timeout or no network. Read `result.error`. |
| `status` is `401` | The API key is missing or not valid. Check `apiKey`. |
| `status` is `204` | No ad matched. This is a normal result. Hide the slot. |
| Ads are always test ads | Set `production = true` in the constructor. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.