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

# Set up in-app messages on Android

> The Android push library syncs each user's in-app messages to your Android app. Your app shows them in its own views and reports impressions, clicks, and dismissals back to Hightouch.

Setting up iOS too? See [Set up in-app messages on iOS](https://docs.hightouch.com/native-delivery/in-app/ios.md).

## Overview

In-app messages arrive in your app as data, not as finished screens. The SDK keeps a local inbox of each user's messages up to date and calls your code when it changes. Your app picks the messages for a screen, lays them out with its own UI, and reports what the user did with them.

Each message carries the fields from its template, such as a headline, an image URL, and a button label, keyed by the names your marketing team agreed with you. See [What your app receives](https://docs.hightouch.com/native-delivery/in-app/templates.md#what-your-app-receives).

## Before you begin

* **Push setup:** Complete [Set up Android push notifications](https://docs.hightouch.com/native-delivery/push-android.md) through **Identify users on login and logout**. The SDK fetches a user's messages only for a device that has an FCM token and has called `identify`.
* **Android 5.0 or later:** The SDK supports API level 21 and later. In-app messages need a version of `android-push` that includes `HightouchMessages`.
* **A template:** Agree with your marketing team on the templates your app supports, and the key of each field. See [Build an in-app template](https://docs.hightouch.com/native-delivery/in-app/templates.md).

## Turn on in-app messages

Add a `HightouchMessagesConfig` to the `HightouchPushConfig` you already pass to `HightouchPush.initialize`, in your `Application` class's `onCreate`:

```kotlin theme={null}
import android.app.Application
import com.hightouch.analytics.kotlin.android.Analytics
import com.hightouch.analytics.kotlin.push.HightouchPush
import com.hightouch.analytics.kotlin.push.HightouchPushConfig
import com.hightouch.analytics.kotlin.push.messages.HightouchMessagesConfig
import com.hightouch.analytics.kotlin.push.messages.HightouchMessagesListener

class MyApplication : Application() {
    // The SDK keeps only a weak reference to the listener, so hold it in a field.
    private val messagesListener = HightouchMessagesListener { change ->
        // Reload any screen that shows in-app messages.
    }

    override fun onCreate() {
        super.onCreate()

        val analytics = Analytics("YOUR_WRITE_KEY", this) {
            apiHost = "YOUR_API_HOST/v1"
            cdnHost = "YOUR_API_HOST/v1"
        }

        val messagesConfig = HightouchMessagesConfig.Builder()
            .setListener(messagesListener)
            .setSyncOnForeground(true)
            .build()

        HightouchPush.initialize(
            analytics = analytics,
            config = HightouchPushConfig.Builder("YOUR_HIGHTOUCH_APP_ID")
                .setMessages(messagesConfig)
                .build(),
        )
    }
}
```

Initialize in `Application.onCreate`. If Android starts your app for a silent push and `initialize` hasn't run, the SDK ignores the push.

`HightouchMessagesConfig.Builder` takes these options:

| Option | What it does | Default |
| - | - | - |
| **`setListener`** | Receives a `HightouchMessagesChange` whenever the inbox gains, changes, or loses a message. Callbacks run on the main thread. | None |
| **`setSyncOnLaunch`** | Fetches messages each time the SDK initializes. | `true` |
| **`setSyncOnForeground`** | Fetches messages when the app returns to the foreground, at most once per cooldown. | `false` |
| **`setForegroundSyncCooldown`** | Milliseconds between foreground syncs. The minimum is one minute. | 15 minutes |
| **`setMaxStoredMessages`** | The most messages the SDK keeps on the device. | `500` |

Turn on `setSyncOnForeground` unless your app relies on silent pushes alone. Without it, the SDK doesn't fetch new messages for a user who keeps the app in the background until the next launch or silent push.

To listen from a screen instead, call `HightouchMessages.addListener` when it starts and `HightouchMessages.removeListener` when it stops. Pass an object that the screen holds, not a lambda created inline, because the SDK keeps only a weak reference to each listener.

## Keep the inbox up to date

The SDK fetches messages:

* When the app launches, if sync on launch is on.
* When the app returns to the foreground, if sync on foreground is on.
* When a user logs in with `HightouchPush.identify`.
* When a silent push arrives from Hightouch, if the message has push apps selected. See [Refresh inboxes right away](https://docs.hightouch.com/native-delivery/in-app/messages.md#refresh-inboxes-right-away).

Each sync replaces the device's inbox with the user's current messages. The SDK removes messages that left the user's inbox in Hightouch, such as when a campaign ends. It stores messages on the device, so your app can show them without a network connection.

The silent push never shows a notification. If your app has its own `FirebaseMessagingService`, it must forward messages to the SDK. See [Use the SDK alongside another FCM provider](https://docs.hightouch.com/native-delivery/push-android.md#use-the-sdk-alongside-another-fcm-provider). Otherwise, inboxes refresh only on launch and foreground.

To fetch messages yourself, such as on pull to refresh, call `sync`:

```kotlin theme={null}
HightouchMessages.sync(force = true) { outcome ->
    // outcome is HightouchSyncOutcome.Changed, Unchanged, or Failed
}
```

## Show messages in your app

Load the messages for a screen with `loadMessages`, which reads off the main thread and calls back on it. Filter by the template's Location ID to get the messages for one placement:

```kotlin theme={null}
HightouchMessages.loadMessages(
    HightouchMessageQuery(locationId = "home_banner", limit = 1)
) { messages ->
    val message = messages.firstOrNull()
    if (message == null) hideBanner() else showBanner(message)
}
```

From a coroutine, call the suspending version instead: `val messages = HightouchMessages.loadMessages(HightouchMessageQuery())`.

The SDK returns messages sorted by priority, then by most recent, and leaves out expired messages. A `HightouchMessageQuery` also takes `variantSlug`, the template's key, to load only messages built from one template. `HightouchMessages.messages(query)` reads synchronously, but it can block right after startup, so prefer `loadMessages` on the main thread.

Read the fields from the message's `content`, a `JsonElement` from kotlinx.serialization. Each element's `tag` is a field key from the template:

```kotlin theme={null}
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull

fun HightouchMessage.element(key: String): JsonObject? =
    ((content as? JsonObject)?.get("elements") as? JsonArray)
        ?.filterIsInstance<JsonObject>()
        ?.firstOrNull { (it["tag"] as? JsonPrimitive)?.contentOrNull == key }

fun JsonObject.string(name: String): String? = (get(name) as? JsonPrimitive)?.contentOrNull

val headline = message.element("headline")?.string("text")
val imageUrl = message.element("hero")?.string("mediaUrl")
```

A field the marketer left empty, with no default, isn't in `elements`. Give your views a fallback for every optional field.

## Report impressions, clicks, and dismissals

The SDK doesn't know when your app shows a message, so report each interaction yourself. These events power the **Impressions**, **Clicked**, and **Dismissed** metrics in Hightouch, and they're written to your warehouse.

```kotlin theme={null}
// When the message is on screen, not when it's loaded.
HightouchMessages.trackImpression(message.messageId)

// When the user taps the message or one of its buttons.
HightouchMessages.trackClick(message.messageId, identifier = "cta")

// When the user closes the message.
HightouchMessages.trackDismissed(message.messageId)
```

Your app performs the tap's action itself, such as opening a screen. Pass an `identifier` to `trackClick` to tell buttons apart in your warehouse data. It defaults to `default`.

`trackDismissed` removes the message from the device, and Hightouch removes it from the user's other devices. The user doesn't receive that message again, even if they leave and rejoin the audience.

## Tips and troubleshooting

### No messages arrive

The SDK skips a sync when the user isn't identified or the device has no FCM token. Check that:

* Your app calls `HightouchPush.identify` after the user logs in. Users who aren't logged in don't receive in-app messages.
* The user ID matches the primary key of the profile in your Delivery parent model.
* The profile is in the campaign's audience, or has reached the journey's **Send in-app** tile, and the campaign or journey is running.

Then call `HightouchMessages.sync(force = true)` and check the outcome. If it returns `Unchanged`, the SDK either found no changes or skipped the sync because the user isn't identified or the device has no FCM token.

### A new message takes a while to appear

Without a push app on the message, a device picks it up on its next sync. Turn on `setSyncOnForeground`, or ask your marketing team to [select push apps](https://docs.hightouch.com/native-delivery/in-app/messages.md#refresh-inboxes-right-away) on the message.

### Messages stop updating after a while

The SDK keeps a weak reference to your listener. A lambda that nothing else holds is garbage collected, and your app stops hearing about changes. Store the listener in a field of a long-lived object, such as your `Application`.

## Next steps

* [Build an in-app template](https://docs.hightouch.com/native-delivery/in-app/templates.md): the fields and keys your app reads.
* [Send an in-app campaign](https://docs.hightouch.com/native-delivery/in-app/campaigns.md): send a message to your test profile to check the integration end to end.
