# Android API

> Every public class, function and property in the three Android modules (core, UI and FCM), with signatures, parameters and threading notes.

This page lists every public symbol in the Android SDK, version 0.4.0, grouped by area. It is written from the module source.

| Module | Package | Use it for |
|---|---|---|
| `herald-core` | `com.herald.sdk`, `com.herald.sdk.push` | Everything except UI and FCM |
| `herald-ui` | `com.herald.ui` | The default feed and in-app views (Jetpack Compose) |
| `herald-fcm` | `com.herald.fcm` | FCM token sync and notification display |

## Threading

- Every function on `Herald` can be called from any thread, returns at once and never throws. Work runs in call order on one background thread named `herald-sdk`. Errors are logged.
- Calls made before `configure` are kept, up to 1,000, and applied in order once it runs. Later ones are dropped with one warning.
- `requestPushAuthorization` must be called from the main thread. Presenters are called on the main thread.
- Functions are annotated `@JvmStatic` and, where they have defaults, `@JvmOverloads`, so Java can call `Herald.track("x")`.

## Setup

### `Herald.configure`

```kotlin
fun configure(context: Context, appKey: String, endpoint: String, options: HeraldOptions = HeraldOptions())
```

Starts the SDK. Call once, from `Application.onCreate`. Later calls are ignored with a warning. Registers activity lifecycle callbacks for sessions, flushing and in-app display.

| Parameter | Type | Description |
|---|---|---|
| `context` | `Context` | Any context; the application context is used |
| `appKey` | `String` | The connection's app key, from the **Mobile SDK** card |
| `endpoint` | `String` | Your Herald base URL, for example `https://YOUR_HERALD_HOST` |
| `options` | `HeraldOptions` | Settings; defaults below |

```kotlin
Herald.configure(
    this,
    appKey = "YOUR_APP_KEY",
    endpoint = "https://YOUR_HERALD_HOST",
    options = HeraldOptions(deviceDataCollection = DeviceDataCollection.MINIMAL, logLevel = LogLevel.DEBUG),
)
```

### Constants

| Constant | Value | Description |
|---|---|---|
| `Herald.SDK_VERSION` | `"0.6.0"` | Sent with every batch |
| `Herald.PUSH_PERMISSION_REQUEST_CODE` | `0x4E58` | Deprecated. The SDK reads the permission answer when the activity resumes, so apps don't need this code. It will be removed. |

### `HeraldOptions`

```kotlin
data class HeraldOptions(
    val deviceDataCollection: DeviceDataCollection = DeviceDataCollection.STANDARD,
    val flushIntervalSeconds: Long = 10,
    val flushAt: Int = 20,
    @Deprecated("Use foregroundSessionTimeoutMinutes and backgroundSessionTimeoutMinutes")
    val sessionTimeoutMinutes: Long = 30,
    val inAppMinimumIntervalSeconds: Long = 30,
    val logLevel: LogLevel = LogLevel.WARN,
    val trackExternalPushes: Boolean = true,
    val foregroundSessionTimeoutMinutes: Long? = null,
    val backgroundSessionTimeoutMinutes: Long? = null,
    val trackLifecycleEvents: Boolean = true,
    val trackDeepLinks: Boolean = true,
    val trackDeepLinkQuery: Boolean = false,
    val maxQueuedEventAgeDays: Long = 30,
)
```

| Property | Description |
|---|---|
| `deviceDataCollection` | `STANDARD` sends tier 1 and tier 2 device data; `MINIMAL` sends tier 1 only |
| `flushIntervalSeconds` | Seconds between automatic flushes while an activity is started |
| `flushAt` | Queued event count that starts a flush |
| `sessionTimeoutMinutes` | Deprecated in 0.6.0. Used for each timeout below that is null (the default), so setting it alone, in the constructor or in `copy`, sets both |
| `inAppMinimumIntervalSeconds` | Minimum seconds between two triggered in-app messages |
| `logLevel` | Lowest level written to Logcat |
| `trackExternalPushes` | 0.6.0+. `herald-fcm` records an FCM message that isn't from Herald and carries a notification as `$external_push` when it reaches the app, so the push limit counts it. Data-only messages are never recorded. |
| `foregroundSessionTimeoutMinutes` | Minutes of inactivity in the foreground before the next activity starts a new session. A cold start within it of the last activity continues the session. 0.6.0 and later. |
| `backgroundSessionTimeoutMinutes` | Minutes in the background before the next activity starts a new session. 0.6.0 and later. |
| `trackLifecycleEvents` | Sends `$app_installed`, `$app_updated`, `$app_opened`, `$app_foreground` and `$app_background` ([Lifecycle events](/docs/reference/event-payload#lifecycle-events)). Default `true`. 0.6.0 and later. |
| `trackDeepLinks` | Sends `$deep_link_opened` when a deep link goes through `openUrl` or a notification tap. Default `true`. 0.6.0 and later. |
| `trackDeepLinkQuery` | Adds the link's query string to `$deep_link_opened`. Default `false`, because a query can hold personal data. 0.6.0 and later. |
| `maxQueuedEventAgeDays` | Queued events older than this are dropped before a batch is built and counted in `dropped`; Herald rejects SDK events more than 30 days old. Default 30. 0.6.0 and later. |

### Enums

```kotlin
enum class DeviceDataCollection { STANDARD, MINIMAL }
enum class LogLevel { DEBUG, INFO, WARN, ERROR, NONE }
enum class SubscriptionChannel { PUSH, EMAIL, SMS }
enum class SubscriptionState { SUBSCRIBED, UNSUBSCRIBED, OPTED_IN }
```

## Identity

| Function | Description |
|---|---|
| `fun identify(userId: String, traits: Map<String, Any?> = emptyMap())` | Identifies the user. A different ID ends the session, clears the previous user's token, cards and messages, and starts a new session. Sends the push token again for the new user, and fetches messages when the device was anonymous. |
| `fun setUserToken(token: String?)` | Identity verification token for the identified user (hex HMAC-SHA256 of the External ID, from your backend). Call immediately after `identify`. Events the user queued before the token arrived are sent with it, and a new token starts a fetch of the user's cards and messages. |
| `fun reset()` | Signs the user out: ends the session, clears the External ID, token, cards, messages and pending messages, takes down a message on screen, starts a new anonymous session and sends the push token again. The device ID stays. |
| `val heraldId: String?` | The User ID of the identified person, such as `"7K3M-9QXA"`, for a "Support ID" line on your settings or help screen. `null` until the first accepted batch for the user the batch is verified as (any claimed user under Off; never under Optional without a token), and again after `reset()` or a switch to another user. Cached across launches. Read-only and safe from any thread. See [Support ID](/docs/concepts/users-and-identity#support-id). |

`userId` is 1 to 200 characters. Traits follow the attribute rules below.

## Events and attributes

| Function | Description |
|---|---|
| `fun track(event: String, properties: Map<String, Any?> = emptyMap(), schemaVersion: String? = null)` | Custom event; evaluates event triggers. Name 1 to 255 characters. `schemaVersion` (0.6.0 and later) names the [event schema](/docs/concepts/event-schemas) version to check it against, such as `"1-0-0"`; `null` (the default) means the latest. A value that isn't a version like `1-0-0` is left off with a debug log; the event is still sent. |
| `fun screen(name: String, properties: Map<String, Any?> = emptyMap())` | Screen view. Name 1 to 255 characters. |
| `fun trackExternalPush(messageId: String? = null, category: ExternalPushCategory = ExternalPushCategory.OTHER, source: String? = null)` | 0.6.0+. A push your app sent itself, as `$external_push`, so the push limit counts it. `messageId` up to 200 characters (the same ID your backend reports, so it counts once), `source` up to 100; longer values are logged and skipped. `ExternalPushCategory` is `TRANSACTIONAL`, `MARKETING` or `OTHER`. Never include the push's title or body. |
| `fun handleExternalPush(data: Map<String, String>, hasNotification: Boolean, fcmMessageId: String?)` | 0.6.0+. Records a non-Herald FCM message with a notification as `$external_push` (with `trackExternalPushes` on). `herald-fcm` calls it; call it from `onMessageReceived` only in your own FirebaseMessagingService. |
| `fun trackPurchase(productId: String, price: Double, currency: String, quantity: Int = 1, properties: Map<String, Any?> = emptyMap())` | Purchase. Product ID 1 to 255 characters, finite price, 3-letter currency (upper-cased), quantity 1 or more. |
| `fun setAttribute(key: String, value: Any?)` | One attribute |
| `fun setAttributes(attributes: Map<String, Any?>)` | Several attributes, merged into the profile |
| `fun setEmail(email: String?)` | Reserved `$email`; must be a valid address |
| `fun setPhone(phone: String?)` | Reserved `$phone`; must be E.164, such as `+15551234567` |
| `fun setSubscription(channel: SubscriptionChannel, state: SubscriptionState)` | Opt-in state for a channel. A push opt-in waits for the FCM token; an opt-out is sent at once. |
| `fun setLocation(latitude: Double, longitude: Double)` | A location your app obtained, stored on the device record as `$latitude` and `$longitude`. Out-of-range values are logged and skipped. |

Property values: strings, numbers, booleans, null, lists and maps; numbers must be finite; keys up to 255 characters. Attribute values: `String`, `Number`, `Boolean`, `null`, or a `List` or `Array` of `String`; keys 1 to 255 characters. An invalid `$email` or `$phone` is dropped with a warning and the other keys are sent.

## Consent

0.6.0+.

```kotlin
fun setConsent(basis: ConsentBasis, documentId: String? = null, documentVersion: String? = null)
fun clearConsent()
```

Records the lawful basis your app collects data under. `ConsentBasis` is `CONSENT`, `CONTRACT`, `LEGAL_OBLIGATION`, `VITAL_INTERESTS`, `PUBLIC_TASK` or `LEGITIMATE_INTERESTS` (the GDPR lawful bases). `documentId` and `documentVersion` name your policy or terms, at most 100 characters each; a longer one is logged and the call skipped. The record and the time of the call are persisted and sent in each batch's `context.consent` until `clearConsent()`. Herald keeps it on the device and on the person, where admins see it on the person's page.

This is a record for your compliance, not enforcement: it doesn't change what the SDK collects. Use `deviceDataCollection` or `setEnabled(false)` for that. See [Consent and opt-out](/docs/data-and-privacy/consent-and-opt-out).

## Remote config

0.6.0+. The SDK fetches the app's SDK settings (Settings, SDK settings in the console) at launch and on a foreground at most once an hour, with no user or device id. It caches the last good response on disk and applies the cached one at launch, before the fetch. A remote value overrides `flushIntervalSeconds`, `foregroundSessionTimeoutMinutes`, `backgroundSessionTimeoutMinutes`, `deviceDataCollection`, `trackLifecycleEvents`, `trackExternalPushes` or `trackDeepLinks`; a setting left at "Use app's value" keeps yours. A network or parse error keeps what is applied, and startup never waits for the fetch. Nothing is fetched while `setEnabled(false)` is in effect.

With "Collect events" off, the SDK records and sends nothing, skips message syncs and clears its queue. Push tokens and subscription changes are still queued, not sent, and go out when collection resumes, with the current push token, so a device that registered or unsubscribed meanwhile isn't lost. It keeps fetching config, so turning it back on resumes collection. The fetch runs off the SDK thread, so sessions and events never wait for it. The cached settings belong to the app key they were fetched with: a different key starts from your options.

```kotlin
val remoteConfigVersion: String?
```

The version of the settings in use (cached or fetched), for debugging; null before any was fetched.

## Data control

| Function | Description |
|---|---|
| `fun flush()` | Sends queued events now, unless a retry delay is running |
| `fun setEnabled(enabled: Boolean)` | `false` sends one best-effort push unsubscribe for the device, then stops all collection, sending and display and hides cached content cards until set back to `true`. `true` re-sends the push token and a push subscription of subscribed when the device still has its token and notifications are enabled. Persisted. |
| `fun isEnabled(context: Context): Boolean` | `false` after `setEnabled(false)` or `wipeData()` until `setEnabled(true)`. Reflects those calls at once; otherwise reads the saved opt-out from disk, so it works before `configure`. `herald-fcm` checks it and does not show Herald pushes while it is `false`; check it too if you show them yourself. Cheap and safe from any thread. |
| `fun wipeData()` | Sends one best-effort push unsubscribe for the device, then deletes every file and record the SDK keeps, including queued events and cached cards, and leaves the SDK off. `setEnabled(true)` starts again with a new device ID. |

## Push

### requestPushAuthorization

```kotlin
fun requestPushAuthorization(activity: Activity)
```

Call from the main thread. On Android 13 and later, when `POST_NOTIFICATIONS` is not granted, shows the permission prompt and records the answer when the activity resumes: `OPTED_IN` when allowed (sent once the FCM token exists), `UNSUBSCRIBED` when denied. Below Android 13, or when already granted, records whether notifications are enabled for the app, without a prompt. From the first prompt on, device data reports the permission as `authorized` or `denied` instead of `not_determined`.

### setPushToken

```kotlin
fun setPushToken(token: String)
```

The FCM registration token, 1 to 4,096 characters. `herald-fcm` calls it for you.

### handleNotificationIntent

```kotlin
fun handleNotificationIntent(intent: Intent?): Boolean
```

Call from the activity that receives notification taps, in `onCreate` and `onNewIntent`, after `configure`. Returns `true` when the intent came from a Herald notification. The intent must carry this install's tap token, a random secret that `herald-fcm` and `putInto` add; an intent without it, such as one another app sends to your exported launcher activity, is ignored and returns `false`. It logs a push `open` (and then a `button` with the action ID when an action button was tapped), evaluates `push_open` triggers, cancels the notification and opens the deep link. It removes the Herald extras from the intent, so a redelivered intent is not counted twice.

### handleRemoteMessage

```kotlin
fun handleRemoteMessage(data: Map<String, String>): Boolean
```

Handles a Herald sync push: a data-only FCM message with `herald_sync` set to `"1"`. Returns `true` and refreshes content cards and in-app messages; returns `false` for any other message. It never shows a notification or logs an open, and skips a sync push that arrives within 30 seconds of the last one. Called off the main thread, as `onMessageReceived` is, it returns once the refresh has finished, or after 8 seconds at most; on the main thread it returns at once. `herald-fcm` calls it for you; call it from `onMessageReceived` only in your own `FirebaseMessagingService`. See [Silent push](/docs/push-notifications/silent-push).

### canPostLiveUpdates

```kotlin
fun canPostLiveUpdates(): Boolean
```

0.7.0+. Whether Android may show Live Updates (Live Activity campaigns on Android) as promoted notifications, with a status bar chip and a place at the top of the lock screen: `NotificationManager.canPostPromotedNotifications()`. `false` below Android 16 (API 36), before `configure`, or when the person turned it off for your app; `herald-fcm` still shows the Live Update as an ongoing notification then. See [Live Activities on Android](/docs/live-activities/android).

### `HeraldPushPayload`

```kotlin
package com.herald.sdk.push

data class HeraldPushPayload(
    val decisionId: String?, val messageId: String?, val deeplink: String?,
    val title: String?, val body: String?, val imageUrl: String?,
) {
    @JvmOverloads fun putInto(intent: Intent, context: Context? = null): Intent
    companion object {
        const val KEY_DECISION_ID = "nexus_decision_id"
        const val KEY_MESSAGE_ID = "herald_message_id"
        const val KEY_DEEPLINK = "deeplink"
        const val KEY_TITLE = "title"
        const val KEY_BODY = "body"
        const val KEY_IMAGE = "image"
        const val KEY_NOTIFICATION_ID = "herald_notification_id"
        const val KEY_ACTION_ID = "herald_action_id"
        const val KEY_TAP_TOKEN = "herald_tap_token"
        const val NOTIFICATION_TAG = "herald"
        fun fromData(data: Map<String, String>): HeraldPushPayload?
        fun fromIntent(intent: Intent?): HeraldPushPayload?
    }
}
```

The Herald fields of an FCM data message and of a notification tap intent. `fromData` and `fromIntent` return `null` when the message has neither a decision ID nor a message ID. `putInto` copies the decision ID, message ID and deep link into an intent as extras, plus the tap token `handleNotificationIntent` requires. It reads the token through `context`, or through the context passed to `configure` when `context` is `null`. Use these when you build your own notifications, and always build the tap intent with `putInto`: copying the extras by hand leaves out the token, so the tap is not counted and its link is not opened.

### `PushTokenSource`

```kotlin
package com.herald.sdk.push

object PushTokenSource {
    @Volatile var request: (() -> Unit)?
}
```

For `herald-fcm`, not for apps. `HeraldMessagingService.syncToken` sets it to a fetch of the current FCM token. The SDK calls it when `setEnabled(true)` runs with notifications allowed and no stored token (after `wipeData()`), because FCM does not issue an unchanged token again on its own. If you use your own `FirebaseMessagingService` without `syncToken`, set it to a function that fetches the token and calls `Herald.setPushToken`.

## Content cards

| Member | Description |
|---|---|
| `val contentCards: StateFlow<List<ContentCard>>` | The current user's cards, unexpired and not dismissed, in server order |
| `fun refreshContentCards()` | Fetches cards and in-app messages now. The SDK also fetches at session start and when an anonymous device is identified. |
| `fun logImpression(card: ContentCard)` | Logs an impression and sets `viewed`. At most one impression per card per session is sent. |
| `fun logClick(card: ContentCard)` | Logs a click and sets `clicked` |
| `fun logDismissal(card: ContentCard)` | Logs a dismissal and hides the card on this device |
| `fun logVideoPlay(card: ContentCard)` | Logs `video_play` for a custom display (0.6.0); `herald-ui` does it once per play |
| `fun logVideoComplete(card: ContentCard)` | Logs `video_complete` for a custom display (0.6.0) |

A call for a card the SDK no longer has is logged and ignored.

### ContentCard

```kotlin
data class ContentCard(
    val id: String, val type: ContentCardType,
    val title: String?, val body: String?, val imageUrl: String?, val cta: String?, val url: String?,
    val extras: Map<String, Any?>, val pinned: Boolean, val dismissible: Boolean, val categories: List<String>,
    val createdAt: Long, val expiresAt: Long?,
    val viewed: Boolean, val clicked: Boolean, val dismissed: Boolean, val decisionId: String?,
    val videoUrl: String? = null, val videoPosterUrl: String? = null, // the poster is the same as imageUrl (0.6.0)
    val videoAutoplay: Boolean = false,                               // muted and looped in ContentCardFeed while half visible
    val credit: MediaCredit? = null,                                  // MediaCredit(name: String, profileUrl: String?, sourceUrl: String?)
)

enum class ContentCardType { CLASSIC, CAPTIONED_IMAGE, IMAGE_ONLY }
```

Timestamps are epoch milliseconds. `url` is the deep link or web URL opened on click. `decisionId` is sent back with interactions.

## In-app messages

| Member | Description |
|---|---|
| `var inAppMessageDelegate: InAppMessageDelegate?` | Decides whether a message shows now, later or never |
| `var inAppMessagePresenter: InAppMessagePresenter?` | Draws messages; `herald-ui` installs the default. Messages wait while it is `null`; setting a presenter offers any pending message. |
| `fun showNext()` | Offers the highest-priority pending message now (ties: the one pending longest), ignoring the minimum interval. The delegate is asked again. Does nothing while a message is on screen. |
| `var deepLinkHandler: ((String) -> Boolean)?` | Opens Herald deep links: push taps, card clicks and in-app button and body clicks. Return `true` when your app handled the link; when `null` or returning `false`, the SDK opens it with `ACTION_VIEW`. Called on the thread that opens the link, the main thread for taps and clicks. Same semantics as iOS `deepLinkHandler`. |
| `fun openUrl(url: String)` | Passes the link to `deepLinkHandler`, then, when it is `null` or returns `false`, opens it with an `ACTION_VIEW` intent. Presenters use it for clicks. From 0.6.0 it also sends `$deep_link_opened` (`source` `link`; a notification tap's link sends `push`) unless `trackDeepLinks` is off. |
| `fun debugLoadMessages(json: String)` | Debug and preview only. See [Logging and debugging](/docs/operations/logging-and-debugging#preview-messages-without-a-server). |
| `fun debugShowInAppMessage(messageId: String)` | Debug and preview only |

### InAppMessage

```kotlin
data class InAppMessage(
    val id: String, val type: InAppMessageType, val priority: Int,
    val trigger: InAppTrigger, val reEligibility: ReEligibility, val expiresAt: Long?,
    val content: InAppContent, val style: InAppStyle, val decisionId: String?,
)
```

| Type | Definition |
|---|---|
| `InAppMessageType` | `SLIDEUP`, `MODAL`, `FULL`, `HTML` |
| `InAppTrigger` | `data class InAppTrigger(val type: TriggerType, val event: String?, val propertyFilters: List<PropertyFilter>)` |
| `TriggerType` | `SESSION_START`, `EVENT`, `PUSH_OPEN` |
| `PropertyFilter` | `data class PropertyFilter(val key: String, val op: FilterOperator, val value: Any?)` |
| `FilterOperator` | `EQ`, `NEQ`, `GT`, `GTE`, `LT`, `LTE`, `CONTAINS`, `EXISTS` |
| `ReEligibility` | `data class ReEligibility(val mode: ReEligibilityMode, val hours: Double?)` |
| `ReEligibilityMode` | `ONCE`, `AFTER_HOURS` |
| `InAppContent` | `data class InAppContent(val header: String?, val body: String?, val imageUrl: String?, val buttons: List<InAppButton>, val html: String?, val slideFrom: String?, val dismissAfterSeconds: Double?, val videoUrl: String? = null, val videoPosterUrl: String? = null, val credit: MediaCredit? = null)` |
| `InAppButton` | `data class InAppButton(val id: String, val text: String, val action: ButtonAction)` |
| `ButtonAction` | `data class ButtonAction(val type: ButtonActionType, val value: String?)` |
| `ButtonActionType` | `DEEPLINK`, `URL`, `CLOSE` |
| `InAppStyle` | `data class InAppStyle(val backgroundColor: String?, val textColor: String?, val buttonColor: String?, val buttonTextColor: String?, val cornerRadius: Double?)` |

`slideFrom` is `"top"` or `"bottom"`; slideups come from the bottom unless it is `"top"`. Style colors are hex strings such as `#101828`; `null` means use the theme. A filter on a missing or null property is false for every operator, `EXISTS` included.

### InAppMessageDelegate

```kotlin
fun interface InAppMessageDelegate {
    fun shouldDisplay(message: InAppMessage): InAppDisplayDecision
}

enum class InAppDisplayDecision { DISPLAY, LATER, DISCARD }
```

Asked on the main thread when a message is about to appear. Return quickly: the SDK waits for the answer. It can be asked more than once for the same message. If it throws, the message shows and the error is logged.

| Decision | Effect |
|---|---|
| `DISPLAY` | Show now |
| `LATER` | Keep it pending; offered again automatically or with `showNext()` |
| `DISCARD` | Drop this occurrence; the message stays eligible for its next trigger |

### InAppMessagePresenter, InAppMessageCallbacks

```kotlin
fun interface InAppMessagePresenter {
    fun present(activity: Activity, message: InAppMessage, callbacks: InAppMessageCallbacks): Boolean
    fun dismissCurrent() {}
}

interface InAppMessageCallbacks {
    fun onImpression()
    fun onClick(buttonId: String?)
    fun onVideoPlay() {}      // 0.6.0, optional
    fun onVideoComplete() {}  // 0.6.0, optional
    fun onDismiss()
}
```

Called on the main thread with the resumed activity. Return `true` only when the message is on screen; Herald then marks it shown. Return `false` and it stays pending and is retried on the next activity resume. `dismissCurrent` takes the message down without user action (sign-out or user switch).

Report through the callbacks: `onImpression` when the message becomes visible, `onClick(null)` for a body tap or `onClick(id)` for a button, and `onDismiss` exactly once when it leaves the screen for any reason. A dismissal is logged only when nothing was clicked. `onVideoPlay` and `onVideoComplete` log `video_play` and `video_complete` for a message with a video, once per play; both have empty defaults.

## `herald-ui`

Every composable here reads `LocalHeraldTheme` unless a theme is passed in.

### ContentCardFeed

```kotlin
@Composable
fun ContentCardFeed(
    modifier: Modifier = Modifier,
    filter: (ContentCard) -> Boolean = { true },
    order: Comparator<ContentCard> = ContentCardFeedDefaults.Order,
    onCardClick: (ContentCard) -> Unit = ContentCardFeedDefaults.OpenUrl,
    contentPadding: PaddingValues = PaddingValues(LocalHeraldTheme.current.spacing),
    emptyContent: @Composable () -> Unit = { /* "No updates right now" */ },
    cardContent: @Composable (card: ContentCard, onClick: () -> Unit) -> Unit = { card, onClick -> ContentCardFeedDefaults.Card(card, onClick) },
)
```

| Parameter | Description |
|---|---|
| `modifier` | Applied to the list |
| `filter` | Keeps the cards it returns `true` for |
| `order` | Sort order; pinned first, then newest, by default |
| `onCardClick` | Runs after the click is logged; opens the card URL by default |
| `contentPadding` | Padding around the list |
| `emptyContent` | Shown when there are no cards |
| `cardContent` | Draws one card; call `onClick` when it is tapped |

Impressions are logged once per card per session when at least half the card is visible. Dismissible cards can be swiped away, or dismissed with the TalkBack "Dismiss" action.

### ContentCardFeedDefaults

```kotlin
object ContentCardFeedDefaults {
    val Order: Comparator<ContentCard>          // pinned first, then newest
    val OpenUrl: (ContentCard) -> Unit          // Herald.openUrl(card.url)
    @Composable fun Card(card: ContentCard, onClick: () -> Unit)   // default view for card.type
}
```

### Card composables

```kotlin
@Composable fun ClassicContentCard(card: ContentCard, onClick: () -> Unit)
@Composable fun CaptionedImageContentCard(card: ContentCard, onClick: () -> Unit)
@Composable fun ImageOnlyContentCard(card: ContentCard, onClick: () -> Unit)
```

Cards are clickable only when they have a `url`. An image-only card's TalkBack label is its title, else `extras["alt"]`.

### `HeraldInAppPresenter`

```kotlin
class HeraldInAppPresenter @JvmOverloads constructor(
    var theme: HeraldTheme = HeraldTheme(),
    var customViews: Map<InAppMessageType, InAppMessageContent> = emptyMap(),
) : InAppMessagePresenter {
    companion object {
        @JvmStatic @JvmOverloads
        fun install(theme: HeraldTheme = HeraldTheme(), customViews: Map<InAppMessageType, InAppMessageContent> = emptyMap()): HeraldInAppPresenter
    }
}

typealias InAppMessageContent = @Composable (message: InAppMessage, actions: InAppMessageActions) -> Unit
```

`install` creates the presenter and sets it as `Herald.inAppMessagePresenter`. The presenter draws in an overlay on the resumed activity, which must be a `ComponentActivity`. `customViews` replaces the default view per message type. If the activity is destroyed while a message is up, the message is shown again on the next activity.

### InAppMessageActions

```kotlin
interface InAppMessageActions {
    fun buttonClicked(button: InAppButton)
    fun bodyClicked(url: String? = null)
    fun clicked(buttonId: String)
    fun dismiss()
    fun videoPlayed() {}     // 0.6.0, optional
    fun videoCompleted() {}  // 0.6.0, optional
}
```

| Function | Logs | Then |
|---|---|---|
| `buttonClicked` | A button click | Opens the deep link or URL, then dismisses |
| `bodyClicked` | A body click | Opens `url` when given, then dismisses |
| `clicked` | A button click | Keeps the message up (the HTML bridge's `herald.click(id)`) |
| `dismiss` | A dismissal, only when nothing was clicked | Takes the message down |
| `videoPlayed` | `video_play` | Nothing; the default views call it once per play |
| `videoCompleted` | `video_complete` | Nothing; the default views call it when the video ends |

### Message views

```kotlin
@Composable fun SlideupMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme)
@Composable fun ModalMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme)
@Composable fun FullScreenMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme)
@Composable fun HtmlMessageView(message: InAppMessage, actions: InAppMessageActions, theme: HeraldTheme)
```

The default view for each type, public so a custom view can wrap one. A slideup dismisses when swiped toward its edge; an HTML message has a close button in the top end corner.

### Theme

```kotlin
@Immutable data class HeraldTheme(
    val lightColors: HeraldColors = HeraldColors.Light,
    val darkColors: HeraldColors = HeraldColors.Dark,
    val typography: HeraldTypography = HeraldTypography(),
    val cornerRadius: Dp = 12.dp,
    val spacing: Dp = 16.dp,
    val darkMode: Boolean? = null,   // null follows the system
) {
    @Composable fun colors(): HeraldColors
}

@Immutable data class HeraldColors(
    val background: Color, val surface: Color, val onSurface: Color, val onSurfaceVariant: Color,
    val accent: Color, val onAccent: Color, val outline: Color, val scrim: Color,
) { companion object { val Light: HeraldColors; val Dark: HeraldColors } }

@Immutable data class HeraldTypography(
    val title: TextStyle,    // 17 sp semibold
    val body: TextStyle,     // 15 sp
    val button: TextStyle,   // 15 sp semibold
    val caption: TextStyle,  // 13 sp
)

val LocalHeraldTheme: ProvidableCompositionLocal<HeraldTheme>
```

Provide a theme to the feed with `CompositionLocalProvider(LocalHeraldTheme provides theme)` and pass it to `HeraldInAppPresenter`. A message's style fields override the theme for that message; an invalid hex value falls back to the theme.

### String resources

Override these in your app's resources to change or translate them: `herald_close` ("Close"), `herald_dismiss` ("Dismiss"), `herald_feed_empty` ("No updates right now").

## `herald-fcm`

### `HeraldMessagingService`

```kotlin
open class HeraldMessagingService : FirebaseMessagingService() {
    override fun onNewToken(token: String)                     // Herald.setPushToken(token)
    override fun onMessageReceived(message: RemoteMessage)     // shows Herald pushes
    open fun onNonHeraldMessage(message: RemoteMessage)        // other pushes; does nothing by default
    companion object { @JvmStatic fun syncToken(context: Context) }
}
```

Registered by the module's manifest. Subclass it and override `onNonHeraldMessage` to handle your other pushes. Before calling it, 0.6.0+ records such a push as `$external_push` when it carries a notification block (with `trackExternalPushes` on): its `message_id` is the data key `herald_external_id`, else `RemoteMessage.messageId`, and its category is `herald_category`, else `other`. `syncToken` fetches the current FCM token and passes it to `setPushToken`; call it after `configure`. It also sets `PushTokenSource.request`, so the SDK can fetch the token again when it is turned back on after `wipeData()`. It logs a warning and does nothing when Firebase is not initialized.

### `HeraldNotifications`

```kotlin
object HeraldNotifications {
    const val DEFAULT_CHANNEL_ID = "herald_default"
    const val KEY_ACTIONS = "herald_actions"
    const val KEY_CHANNEL_ID = "herald_channel_id"
    const val KEY_STORY = "herald_story"                         // 0.7.0+
    const val STORY_PAGE_ACTION_PREFIX = "herald_story_page_"    // 0.7.0+
    const val TAG = "herald"
    const val LIVE_UPDATE_TAG = "herald_live_update"
    @DrawableRes var smallIcon: Int
    fun createDefaultChannel(context: Context, name: CharSequence = /* herald_default_channel_name */, importance: Int = NotificationManager.IMPORTANCE_DEFAULT)
    fun handleRemoteMessage(context: Context, message: RemoteMessage): Boolean
}

data class HeraldNotificationAction(val id: String, val title: String, val deeplink: String?)
data class HeraldStoryPage(val imageUrl: String, val title: String, val subtitle: String, val deeplink: String?)  // 0.7.0+
```

| Member | Description |
|---|---|
| `smallIcon` | A monochrome drawable for the status bar. `0` (default) uses the `com.google.firebase.messaging.default_notification_icon` meta-data, then the module's bell icon. |
| `createDefaultChannel` | Creates the `herald_default` channel if it does not exist. The name comes from the `herald_default_channel_name` string resource ("Notifications") unless given. |
| `handleRemoteMessage` | Shows a Herald push and returns `true`; returns `false` for other pushes. Blocks while the image downloads, so call it off the main thread (FCM already does). |

`handleRemoteMessage` reads title, body and image from the data keys, else from the FCM notification block. It uses the channel named by `herald_channel_id` or the notification's channel when that channel exists, else the default channel. It shows up to three `herald_actions` buttons. 0.7.0+: a push with `herald_story` (2 to 10 valid pages) shows as a [push story](/docs/push-notifications/push-stories) instead, with Previous and Next buttons handled by the module's `HeraldStoryReceiver`; a tap logs a `button` interaction `herald_story_page_<index>`.

## `herald-geofence`

0.7.0+, not released yet. Opt-in geofence monitoring with Play Services `GeofencingClient`, a separate module so apps that don't use it never depend on Play Services location. See [Geofences](/docs/concepts/geofences).

```kotlin
import com.herald.geofence.disableGeofences
import com.herald.geofence.enableGeofences

fun Herald.enableGeofences()
fun Herald.disableGeofences()
// From Java: HeraldGeofence.enableGeofences(Herald.INSTANCE)
```

`enableGeofences()` downloads the app's geofence list (`GET /api/v1/sdk/geofences`, no location sent) and registers all of them (an app has at most 100, Android's limit). Call it after `configure`, at every launch, once the app holds `ACCESS_FINE_LOCATION` and, on Android 10 and later, `ACCESS_BACKGROUND_LOCATION`; without them the call logs a warning and does nothing. The module adds no permissions to your manifest, only its `GeofenceReceiver`, and never asks for permission. Crossings send `$geofence_enter` / `$geofence_exit` with `geofence_id` and `geofence_name`, at most one per geofence and direction every 5 minutes, and nothing while the SDK is off. The **Geofences** SDK setting set to Off stops monitoring. `disableGeofences()` removes Herald's geofences until `enableGeofences()` is called again.

0.7.0+: it also shows Live Updates (data messages with `herald_type` set to `live_update`) as an ongoing notification on the default channel, tagged `LIVE_UPDATE_TAG`, and returns `true` for them. See [Live Activities on Android](/docs/live-activities/android).

## Related

- [iOS API](/docs/reference/ios-api)
- [Event payload spec](/docs/reference/event-payload)
- [Limits](/docs/reference/limits)
