---
title: "Android Native Integration for Web Widgets"
canonical_url: "https://docs.sportradar.com/resources/widgets/docs/tutorials/android-native-integration"
markdown_url: "https://docs.sportradar.com/resources/widgets/docs/tutorials/android-native-integration.md"
last_updated: "2026-07-27T09:12:12Z"
---

# Android Native Integration for Web Widgets

This guide explains how to host Sportradar web widgets inside a native Android app using Jetpack Compose and `WebView`.

The integration pattern is reusable for all widgets. The only widget-specific parts are:

- the widget name passed to `SIR("addWidget", ...)`
- the props object passed to that widget
- optional loader options (language, theme, adapters, and similar)
- optional JavaScript callbacks such as `onTrack` or `onItemClick`

Follow the Sportradar web / JavaScript widget documentation for the loader bootstrap and `SIR("addWidget", ...)` call. On Android, host that page with a shared `WebView`, which provides layout helpers and JavaScript communication.

## Intended Audience

This tutorial is for:

- **Android developers** integrating Sportradar web widgets into Jetpack Compose apps
- **Technical integrators** who already understand basic [widget integration](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md)
- Developers familiar with `WebView`, Compose `AndroidView`, and JavaScript bridges

## Goals

By completing this tutorial, you will:

- Build a reusable Compose host around `WebView`
- Load Sportradar widget HTML with the correct base URL so assets resolve
- Bridge JavaScript -> Kotlin messages for height and widget callbacks
- Bridge Android -> JavaScript so you can call `SIR(...)` without reloading
- Size the `WebView` to the widget's content height inside native scroll containers
- Swap widgets by changing HTML / props only, not the native host

## Prerequisites

Before starting, ensure you have:

- **Android Studio** with Compose and `WebView` available
- **Client ID** - see [how to obtain one](https://docs.sportradar.com/resources/widgets/docs/tutorials/faq.md#client-id)
- **Basic widget integration experience** - completed the [Getting Started](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md) guide
- Familiarity with the [SIR API](https://docs.sportradar.com/resources/widgets/docs/tutorials/SIR.md) (`addWidget`, `updateWidget`, `setClientTheme`, and related methods)
- A valid **match ID** (or other entity ID) for testing

> **Tip**
>
> For the message bridge shown below, add the Jetpack WebKit dependency:

```toml
[versions]
androidxWebkit = "1.16.0"

[libraries]
androidx-webkit-webkit = { module = "androidx.webkit:webkit", version.ref = "androidxWebkit" }
```

```kotlin
implementation(local.androidx.webkit.webkit)
```

## Overview

The generic integration flow is:

1. **Build the shared Android host**

   Create a reusable `WebView` host with a message bridge, height observer, and optional JavaScript access.

2. **Build the widget HTML page**

   Follow the Sportradar JS widget docs for the `widgetloader` bootstrap and `SIR("addWidget", ...)` call.

3. **Host the page in Compose**

   Load the HTML with `loadDataWithBaseURL(...)` and size the `WebView` from reported content height.

4. **Handle events and live updates (optional)**

   Receive widget callbacks through `SportradarWidgetsSDK`, and optionally call `SIR(...)` from Android without reloading.

### What to implement

The following pieces are enough for an Android integration:

1. The shared Android host `WebView`
2. Widget HTML built according to Sportradar's JS documentation
3. Handling of `onMessage` for height and widget callbacks
4. Optionally a retained `WebView` reference for Android -> JS

> **Note**
>
> You may choose to add code that builds widget HTML from parameters or automatically injects the Sportradar loader bootstrap. Those helpers are useful, but they are not required for a basic implementation.

### Generic vs widget-specific

#### Shared across all widgets

- The shared Android `WebView`
- `SportradarWidgetsSDK` message handling
- Height reporting and native frame sizing
- Base URL loading behavior

#### Changes per widget

- Widget name
- Props
- Loader options
- Optional callbacks

How you store or generate the HTML is an app concern, not part of the host.

## Building the Shared Android Host

The steps below walk through recreating the shared Android host in a reusable way. Capabilities are added progressively. After the host is in place, [Using the Shared Android Host](#using-the-shared-android-host) covers widget HTML, sizing, callbacks, and Android -> JS updates.

The shared Android host around `WebView` should:

- load your HTML with `loadDataWithBaseURL(...)`
- register the `SportradarWidgetsSDK` message bridge with `WebViewCompat.addWebMessageListener(...)`, scoped to trusted origins only
- inject a shared height observer after the page loads
- receive height updates from the page and apply them to the Compose layout
- optionally keep a `WebView` reference for `evaluateJavascript(...)`, which enables Android -> JS communication

### Step 1: Create a shared Android `WebView` host

Before wiring the host, define the inputs it expects:

- `html`: the widget page string you build from Sportradar's JS docs
- `baseUrl`: a strict trusted HTTPS origin such as `https://www.betradar.com`
- a widget mount element such as `#sr-widget`
- `data-sr-height-root` on the element that should drive native auto-height

> **Note**
>
> `SportradarWidgetsSDK` in these examples is just the JavaScript bridge name exposed by Android through `WebViewCompat.addWebMessageListener(...)`. It is not a required Sportradar name. You can rename it to something else such as `srBridge`, as long as the Kotlin side and JavaScript side use the same name consistently.

Start with a Compose host that renders a `WebView`, sizes from reported height, and keeps a reference for later `evaluateJavascript(...)` calls:

```kotlin
var widgetHeightDp by remember { mutableStateOf(1) }
var webViewRef by remember { mutableStateOf<WebView?>(null) }

AndroidView(
    modifier = Modifier.height(widgetHeightDp.dp),
    factory = { context ->
        WebView(context).apply {
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
                WebViewCompat.addWebMessageListener(
                    this,
                    "SportradarWidgetsSDK",
                    setOf(baseUrl),
                    WidgetWebMessageBridge { message ->
                        if (message.type == "height" && message.height != null) {
                            widgetHeightDp = message.height
                        } else {
                            // Handle widget callbacks posted to SportradarWidgetsSDK
                        }
                    },
                )
            }
            loadDataWithBaseURL(baseUrl, html, "text/html; charset=UTF-8;", null, null)
        }
    },
    update = { webViewRef = it },
)
```

Use the reported height to size the `WebView` when the widget sits inside a native scroll container.

> **Warning**
>
> Use a strict HTTPS origin such as `https://www.betradar.com` for `baseUrl`. Avoid `*` and avoid HTTP unless you fully trust the network path.

## Using the Shared Android Host {#using-the-shared-android-host}

With the host in place, build widget HTML and wire it into your Compose UI. The remaining steps keep the Android host generic while leaving widget-specific differences in the HTML / props layer.

### Step 2: Build the widget HTML from the JS docs

Use Sportradar's web widget documentation for:

- the `widgetloader` bootstrap for your client ID
- `SIR("addWidget", selector, widgetName, props)`
- any loader options and callbacks the widget requires

See [Getting Started](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md) and the [SIR API](https://docs.sportradar.com/resources/widgets/docs/tutorials/SIR.md) for the authoritative JavaScript patterns.

A minimal page shape:

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        html, body { margin: 0; padding: 0; }
    </style>
</head>
<body>
    <div id="sr-widget" data-sr-height-root></div>
    <script type="text/javascript">
        // Loader bootstrap + SIR("addWidget", ...) from Sportradar JS docs
    </script>
</body>
</html>
```

> **Tip**
>
> Notes for Android hosting:
>
> - Put `data-sr-height-root` on the element that should drive native auto-height, usually the mount div. The shared Android host can observe that element and report its height back through the JS bridge. If omitted, height can fall back to `document.body`.
> - Keep page backgrounds transparent if you want the Compose background to show through.
> - Replace the example client ID (`sportradar`) with your assigned client ID in production.
> - Keep the page markup minimal. The native host can inject the shared height observer instead of making each widget page responsible for that logic.

### Step 3: Size the host from reported height

`SportradarWidgetsSDK` posts height updates as a string message payload:

```text
height
420
```

Parse them from `onMessage` and apply `Modifier.height(...)`:

```kotlin
WidgetWebMessageBridge { message ->
    if (message.type == "height" && message.height != null) {
        widgetHeightDp = message.height
    } else {
        // Handle non-height widget messages
    }
}
```

Keep the widget HTML minimal and let the shared Android host inject the height observer after the page loads.

Add the injection in your `WebViewClient`:

```kotlin
override fun onPageFinished(view: WebView?, url: String?) {
    super.onPageFinished(view, url)
    view?.evaluateJavascript(installHeightObserverJs, null)
}
```

Use a shared observer script like this:

```javascript
(function() {
    function heightRoot() {
        return document.querySelector("[data-sr-height-root]") || document.body;
    }
    function postHeight() {
        var el = heightRoot();
        var height = Math.ceil(el.getBoundingClientRect().height);
        if (height > 0 && window.SportradarWidgetsSDK && typeof window.SportradarWidgetsSDK.postMessage === "function") {
            window.SportradarWidgetsSDK.postMessage(["height", String(height)].join("\n"));
        }
    }
    new ResizeObserver(postHeight).observe(heightRoot());
    postHeight();
})();
```

That script:

1. Finds the element marked with `data-sr-height-root`
2. Falls back to `document.body` if the marker is missing
3. Measures `getBoundingClientRect().height`
4. Sends the measured height to Android
5. Re-sends height whenever the observed element resizes

#### Android-side validation

Validate that the message came from the main frame and the expected origin before mapping it into your structured event flow:

```kotlin
class WidgetWebMessageBridge(
    private val onMessage: (WidgetBridgeEvent) -> Unit,
) : WebViewCompat.WebMessageListener {
    override fun onPostMessage(
        view: WebView,
        message: WebMessageCompat,
        sourceOrigin: Uri,
        isMainFrame: Boolean,
        replyProxy: JavaScriptReplyProxy,
    ) {
        if (!isMainFrame || sourceOrigin.toString() != "https://www.betradar.com") return

        val payload = message.data ?: return
        val parts = payload.split("\n", limit = 3)
        if (parts.firstOrNull() == "height") {
            val height = parts.getOrNull(1)?.toDoubleOrNull() ?: return
            onMessage(WidgetBridgeEvent(type = "height", height = kotlin.math.ceil(height).toInt()))
        }
    }
}
```

and handle it from the same shared callback:

```kotlin
WidgetWebMessageBridge { message ->
    if (message.type == "height" && message.height != null) {
        widgetHeightDp = message.height
    } else {
        // Handle regular widget callback messages here
    }
}
```

> **Tip**
>
> If you want a fallback until the widget reports its real size, start from a small default or a minimum native height and replace it once the first height message arrives.

### Step 4: Bridge widget callbacks to Kotlin

When the JS docs say to attach callbacks such as `onTrack` or `onItemClick`, forward them into native code through `SportradarWidgetsSDK`:

```javascript
onTrack: function(eventName, eventData) {
    if (window.SportradarWidgetsSDK && typeof window.SportradarWidgetsSDK.postMessage === "function") {
        window.SportradarWidgetsSDK.postMessage(
            ["callback", "onTrack", JSON.stringify([eventName, eventData])].join("\n")
        );
    }
}
```

> **Note**
>
> Payloads should be JSON-serializable. For nested objects, stringify in JS if needed.

```javascript
onItemClick: function(target, data) {
    if (window.SportradarWidgetsSDK && typeof window.SportradarWidgetsSDK.postMessage === "function") {
        window.SportradarWidgetsSDK.postMessage(
            ["callback", "onItemClick", JSON.stringify([String(target), JSON.stringify(data)])].join("\n")
        );
    }
}
```

Handle those messages in the same `onMessage` callback used for height.

This pattern stays the same for all widgets:

1. Implement the callback per the Sportradar JS docs
2. `postMessage` to `SportradarWidgetsSDK` using a simple string protocol
3. Branch on `type` (or equivalent) in Kotlin

Only the callback name and payload shape change per widget.

> **Note**
>
> Learn more about tracking in the [Widget Tracking & Analytics Guide](https://docs.sportradar.com/resources/widgets/docs/tutorials/tracking-guide.md).

### Step 5: Call `SIR(...)` from Android (optional)

To change match, theme, language, or other live props without rebuilding HTML, use the retained `WebView` reference:

```kotlin
webViewRef?.evaluateJavascript(
    """SIR("updateWidget", "#sr-widget", { matchId: $matchId });""",
    null,
)

webViewRef?.evaluateJavascript("""SIR("setClientTheme", "sportradardark");""", null)
// SIR("changeLanguage", "de")
```

> **Warning**
>
> Wait until the page is loaded before evaluating. Prefer these API calls over regenerating the HTML string, which reloads the loader and is slower.

## Example of a widget swap

Swapping widgets should not require changing the shared Android host. Change only the HTML you pass in, and how you interpret the bridge messages.

**LMT Plus**

```javascript
SIR("addWidget", "#sr-widget", "match.lmtPlus", {
    matchId: 61591316,
    layout: "single",
    onTrack: function(eventName, eventData) { /* post to SportradarWidgetsSDK */ }
});
```

**Bet Insights**

```javascript
SIR("addWidget", "#sr-widget", "betInsights", {
    matchId: 68687766,
    integration: "inline",
    onItemClick: function(target, data) { /* post to SportradarWidgetsSDK */ }
});
```

The Android host, height observer, and bridge remain the same.

## Files to copy or recreate

For a minimal integration, these two pieces are enough:

1. A shared Android `WebView` host with height handling and JS bridge registration
2. Your widget HTML, following Sportradar's JS documentation

## Key takeaways

### Keep the host generic

The shared Android `WebView`, `SportradarWidgetsSDK`, height reporting, and base URL handling stay the same across every widget.

### Isolate widget differences

Widget name, props, loader options, and callbacks live in the HTML / props layer only.

### Size from reported height

Use the bridge height messages to drive `Modifier.height(...)` instead of letting the `WebView` stretch arbitrarily inside native layouts.

### Prefer SIR updates over reload

Call `SIR(...)` through the retained `WebView` instead of rebuilding the HTML string for every live update.

## Further reading

### Sportradar widget documentation

- [Getting Started](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md) - loader bootstrap and `addWidget`
- [Global SIR API](https://docs.sportradar.com/resources/widgets/docs/tutorials/SIR.md) - `updateWidget`, themes, language, and other methods
- [Widget Tracking & Analytics Guide](https://docs.sportradar.com/resources/widgets/docs/tutorials/tracking-guide.md) - `onTrack` and analytics patterns
- [Integration Best Practices](https://docs.sportradar.com/resources/widgets/docs/tutorials/integration-best-practices.md) - production hardening
- [FAQ](https://docs.sportradar.com/resources/widgets/docs/tutorials/faq.md) - Client ID, widget names, and entity IDs

### Android platform references

- [WebView](https://developer.android.com/reference/android/webkit/WebView) - hosting web content in native Android UI
- [AndroidView](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary) - embedding platform views in Compose
- [WebViewCompat.addWebMessageListener](https://developer.android.com/reference/androidx/webkit/WebViewCompat#addWebMessageListener\(android.webkit.WebView,java.lang.String,java.util.Set,androidx.webkit.WebViewCompat.WebMessageListener\)) - JavaScript -> Android messaging
