# Android SDK Integration for Mobile In-App Messaging

The preview Engage Mobile SDK connects an Android app to Engage Studio Mobile In-App Messaging. The app sends a trigger event with `trackImmediately`; the SDK requests an offer from Realtime Personalization and renders a supported message in an SDK-owned WebView.

Preview
The native SDK integration is in preview. APIs, artifact distribution, message payloads, and rendering behavior may change before general availability. Follow the release-specific SDK distribution instructions provided by Treasure AI.

## What the SDK Does

The Android SDK is a thin client. Realtime Personalization decides whether to return an experience; the SDK executes the returned decision.

| Responsibility | Owner |
|  --- | --- |
| Audience eligibility and delivery decisions | Realtime Personalization |
| Trigger event and app lifecycle timing | Customer app |
| Message selection from the response | SDK |
| Modal and Banner WebView rendering | SDK |
| Hosted Pages URL rendering | SDK |
| App-specific Deep Link routing | Customer app |
| App-specific custom actions | Customer app |
| Campaign impression, click, and dismiss measurement | SDK |


## Before You Start

Prepare the following values:

- A write-only API key for your Treasure AI account.
- A records endpoint for the account region.
- A Personalization endpoint.
- A Personalization token.
- A database and table for trigger events.
- An event schema that identifies the screen or action that should trigger a message.


The preview artifact version and minimum Android version depend on the SDK build you receive. Confirm them with the release information that accompanies the preview artifact.

## Install the SDK Module

The preview Android SDK ships as a single artifact:

- `com.treasuredata:td-android-sdk` — event collection, buffering, upload, Personalization requests, message models, and the WebView rendering layer for Mobile In-App Messaging and Hosted Pages.


Mobile In-App rendering is part of `td-android-sdk`. There is no separate rendering artifact and no rendering install step.

The preview artifact is published for internal development through the SDK team's distribution workflow. Confirm the repository and version before adding it to a customer application.

## Quick Start

Initialize the core SDK in your `Application` class. Mobile In-App rendering is part of `td-android-sdk`, so no separate rendering install step is required.

```java
import com.treasuredata.android.TreasureData;

public final class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        TreasureData.initializeSharedInstance(
            this,
            "<WRITE_ONLY_API_KEY>",
            "https://<region>.records.in.treasuredata.com"
        );

        TreasureData td = TreasureData.sharedInstance();
        td.setDefaultDatabase("<DATABASE>");
        td.setDefaultTable("<EVENT_TABLE>");
        td.setPersonalizationEndpoint(
            "https://p13n-api.treasuredata.com"
        );
        td.setPersonalizationToken("<PERSONALIZATION_TOKEN>");
        td.enableAutoAppendUniqId();
    }
}
```

Call `trackImmediately` when a screen or event that can trigger a message occurs:

```java
Map<String, Object> event = new HashMap<>();
event.put("event", "pageview");
event.put("screen_name", "home");

TreasureData.sharedInstance().trackImmediately(event);
```

`addEvent` and `uploadEvents` continue to send ordinary events. They do not trigger a Mobile In-App Message.

## Configure the Core APIs

| API or property | Purpose |
|  --- | --- |
| `setPersonalizationEndpoint` | Endpoint used to request a message offer. |
| `setPersonalizationToken` | Read credential used for Personalization. Keep it separate from the write API key. |
| `setDefaultDatabase` / `setDefaultTable` | Default destination used to build trigger requests and ordinary events. |
| `trackImmediately` | Sends a trigger event and requests a message. |
| `setProfileContext` / `setProfileValue` | JSON-serializable values exposed as `window.TDContext`. |
| `TreasureData.setBridgeListener` | Receives app-specific `invoke` callbacks. |
| `openUrl` | Displays a URL that the app already has, such as a URL from a push payload. |


## Message Flow

1. The app calls `trackImmediately(event)`.
2. The Treasure Data Android SDK sends the trigger event to Personalization.
3. Realtime Personalization returns an offer or no offer.
4. The Engage Android module selects one displayable message.
5. The SDK checks the one-message-at-a-time guard.
6. The SDK renders Modal, Banner, or Hosted Pages.
7. The app and message content handle the resulting interaction.


If no campaign matches, the SDK does not display anything. This is a normal result, not an error.

The SDK selects a single displayable message from the response. If another message is already visible, the new message is not displayed.

## Hosted Pages

Hosted Pages is the customer-facing name for a campaign message whose content is loaded from a URL. The Android Engage module displays the URL in a full-screen WebView and injects the configured profile context.

Use Hosted Pages for:

- Coupon pages.
- Stamp cards.
- Lotteries and interactive promotions.
- Surveys and forms.
- Personalized campaign pages.


Hosted Pages does not use the Modal or Banner appearance settings. The hosted page is responsible for providing an appropriate way to leave the experience.

### Campaign-Delivered Hosted Pages

When the app calls `trackImmediately` and Realtime Personalization returns a Hosted Pages offer, the SDK has the campaign identity needed for campaign measurement.

### Direct URL Display

When the app already has a URL, it can call `openUrl`:

```java
Map<String, Object> context = new HashMap<>();
context.put("coupon_id", "abc123");

TreasureData.sharedInstance().openUrl(
    "https://example.com/coupon",
    context
);
```

This is useful for the push-tap path. The URL is displayed in the SDK WebView, but it did not come from a campaign offer, so it does not produce campaign `impression`, `click`, or `dismiss` records.

## Handle Links and Custom Actions

Implement `TDEngageBridgeListener` to receive custom `invoke` actions from message content. Use the Core SDK link handler for app-owned URL navigation:

```java
public final class EngageClient implements TDEngageBridgeListener {
    @Override
    public void handleTDBridgeInvoke(
        @NonNull String name,
        @NonNull Map<String, Object> params
    ) {
        if ("grantPoints".equals(name)) {
            // Check authentication, authorization, and parameter limits.
        }
    }
}

TreasureData td = TreasureData.sharedInstance();
td.setBridgeListener(new EngageClient());
td.setLinkHandler(url -> {
    // Validate and route app-owned schemes here.
    return false;
});
```

The SDK does not interpret the action name or authorize the request. Treat the message content and every parameter as untrusted input. Keep the listener alive for as long as the app needs to receive callbacks.

## Share Profile Context with Message Content

Set JSON-serializable values that the SDK injects into Modal, Banner, and Hosted Pages content as `window.TDContext`.

```java
Map<String, Object> context = new HashMap<>();
context.put("member_tier", "gold");
context.put("points", 1200);

TreasureData.sharedInstance().setProfileContext(context);
```

Follow these rules:

- Use JSON-serializable values only.
- Set the context again after each app launch; it is not persisted by the SDK.
- Clear or replace it when the signed-in customer changes.
- Do not include API keys, tokens, passwords, or values that the Hosted Pages page should not see.
- Pass large numeric identifiers as strings to avoid JavaScript precision loss.


## Handle Screen Changes

The Personalization request is asynchronous. A customer can leave the triggering screen before the response arrives. Use the host application's screen state to decide whether a returned offer is still appropriate to show.

The exact presentation-gate API is part of the preview contract and may change before general availability. Do not display a campaign over a screen that is no longer the screen that triggered the request.

## Register a Push Token

The Android SDK preview includes `registerDeviceToken`. The app still obtains the FCM token and handles notification permission and notification receipt.

```java
@Override
public void onNewToken(String token) {
    TreasureData.sharedInstance().registerDeviceToken(
        token,
        TDPushProvider.FCM,
        "device_tokens"
    );
}
```

The SDK sends a device-token record and flushes it immediately. The preview record uses the following SDK fields:

```json
{
  "td_device_token": "<FCM_TOKEN>",
  "td_push_provider": "fcm"
}
```

This preview record is separate from the sample `token_register` event schema in the existing Mobile Push documentation. Do not treat the two schemas as interchangeable until the canonical Push event contract is finalized.

The app remains responsible for:

- Obtaining the FCM token.
- Requesting notification permission.
- Receiving and displaying the notification.
- Handling notification taps.
- Extracting a URL from a Push payload and passing it to `openUrl` when the tap should open a Hosted Pages.


## Measurement

In the preview SDK flow, campaign measurement is recorded automatically for campaign-delivered messages:

- `impression` — the experience is presented.
- `click` — a supported link or bridge action is used.
- `dismiss` — the experience is closed.


`enableAutoAppendUniqId()` is effectively required when you need to associate these records with an installation. The measurement destination and schema may change before general availability.

For troubleshooting, see [Mobile In-App Troubleshooting](/products/marketing-cloud/engage-studio/channels/mobile-inapp/troubleshooting).

## Minimal Integration Checklist

You can integrate the preview SDK without using a sample application repository.

- Add the preview `td-android-sdk` artifact through the distribution method provided with your SDK build.
- Initialize the core SDK once in the application lifecycle.
- Set the Personalization endpoint, token, database, and event table.
- Configure profile context and the bridge listener only when your content needs them.
- Call `trackImmediately` when the configured screen or event occurs.
- Test Modal, Banner, and Hosted Pages on supported Android devices.
- Register FCM tokens separately if the app uses Mobile Push.
- Verify impression, click, dismiss, Deep Link, and Hosted Pages behavior before release.


The preview artifact names, version, minimum Android version, and distribution URL are release-specific. Use the installation instructions that accompany the artifact rather than a source repository URL.