This is the full developer documentation for Voltra # Plugin Configuration (Android) > Reference for the Android Voltra Expo plugin options, including enableNotifications and widgets, plus widget pre-rendering. The Voltra Expo config plugin accepts Android-specific configuration options in your `app.json` or `app.config.js`: ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "enableNotifications": true, "widgets": [ { "id": "weather", "displayName": "Weather Widget", "description": "Shows current weather conditions", "targetCellWidth": 2, "targetCellHeight": 2, "initialStatePath": "./widgets/weather-initial.tsx", "previewImage": "./assets/widgets/weather-preview.png" } ] } ] ] } } ``` ## Android-Specific Configuration [Section titled “Android-Specific Configuration”](#android-specific-configuration) ### `enableNotifications` (optional) [Section titled “enableNotifications (optional)”](#enablenotifications-optional) Enables Android notification-related manifest plumbing used by Voltra features such as ongoing notifications. When enabled, the config plugin adds: * `android.permission.POST_NOTIFICATIONS` * `android.permission.POST_PROMOTED_NOTIFICATIONS` * `voltra.VoltraOngoingNotificationDismissedReceiver` This does not grant runtime notification permission automatically. Your app still needs to request notification permission on Android 13 and above. For setup and usage examples, see [Managing Android Ongoing Notifications](/android/development/managing-ongoing-notifications). ### `widgets` (optional) [Section titled “widgets (optional)”](#widgets-optional) Array of widget configurations for Home Screen widgets. Each widget will be available in the Android widget picker. **Widget Configuration Properties:** * `id`: Unique identifier for the widget (alphanumeric with underscores only) * `displayName`: Name shown in the widget picker (plain string, or per-locale map; same rules as iOS `widgets[].displayName`) * `description`: Description shown in the widget picker (same rules as `displayName`) * `targetCellWidth`: Target widget width in grid cells (1-5, required) * `targetCellHeight`: Target widget height in grid cells (1-5, required) * `minWidth`: (optional) Minimum width in dp, used on Android 11 and older (defaults to a value derived from `minCellWidth` or `targetCellWidth`) * `minHeight`: (optional) Minimum height in dp, used on Android 11 and older (defaults to a value derived from `minCellHeight` or `targetCellHeight`) * `minCellWidth`: **Deprecated.** (optional) Minimum width in grid cells, converted to dp; prefer `minWidth` * `minCellHeight`: **Deprecated.** (optional) Minimum height in grid cells, converted to dp; prefer `minHeight` * `minResizeWidth`: (optional) Smallest width the user can resize the widget to, in dp (supported on all Android versions) * `minResizeHeight`: (optional) Smallest height the user can resize the widget to, in dp (supported on all Android versions) * `maxResizeWidth`: (optional) Largest width the user can resize the widget to, in dp (Android 12+; ignored on older versions) * `maxResizeHeight`: (optional) Largest height the user can resize the widget to, in dp (Android 12+; ignored on older versions) * `resizeMode`: (optional) Widget resize behavior (`"none"` | `"horizontal"` | `"vertical"` | `"horizontal|vertical"`, default: `"horizontal|vertical"`) * `widgetCategory`: (optional) Widget category (`"home_screen"` | `"keyguard"` | `"home_screen|keyguard"`, default: `"home_screen"`) * `initialStatePath`: (optional) Path to a file that exports initial widget state, or a locale map of paths for localized build-time pre-rendering (see [Widget Pre-rendering](/android/development/widget-pre-rendering)) * `previewImage`: (optional) Path to preview image for widget picker (PNG/JPG/WebP) * `previewLayout`: (optional) Path to custom XML layout for widget picker preview (Android 12+) * `serverUpdate`: (optional) Fetch the widget’s content on a schedule. Without `entry` the server returns a rendered payload; with `entry` it returns plain JSON that the widget renders on the device. `url` is optional — leave it out to supply one at runtime. See [Server-driven widgets](/android/development/server-driven-widgets) for full details. * `url`: The Voltra SSR endpoint URL * `intervalMinutes`: Update interval in minutes (default: `60`, or `15` for a widget with `entry`; minimum 15) * `refresh`: Show a native refresh button (default: `false`) * `appIntent`: (optional, Dynamic Widgets) Configuration parameters the widget reads from `env.configuration`. Each has a `name`, an optional `default` used until `setWidgetConfiguration` changes it, an optional `title` and optional `options` (`[{ "value": "metric", "title": "Metric" }]`), each with a required `title`. Titles accept plain strings or locale maps. See [Localization](/android/development/localization#translate-the-picker-and-configuration-copy) ### Localizing `displayName` and `description` [Section titled “Localizing displayName and description”](#localizing-displayname-and-description) Use a locale map when the widget picker label should be translated: ```json { "widgets": [ { "id": "weather", "displayName": { "en": "Weather", "pl": "Pogoda", "zh-Hans": "天气" }, "description": { "en": "Current weather conditions", "pl": "Aktualne warunki pogodowe", "zh-Hans": "当前天气状况" }, "targetCellWidth": 2, "targetCellHeight": 2 } ] } ``` Use BCP-47-style locale tags such as `en`, `en-US`, `pt-BR`, or `zh-Hans`. Fallback behavior: * Voltra first tries the device locale. * If there is no exact match, it falls back to the language-only match. * If there is still no match, it prefers an English locale such as `en` or `en-US`. * If no English entry exists, it uses the first configured locale. For widget sizing math and widget-picker preview setup (`previewImage`, `previewLayout`), see [Widget Sizing & Previews](/android/api/widget-sizing-and-previews). ## Widget Pre-rendering [Section titled “Widget Pre-rendering”](#widget-pre-rendering) Use `initialStatePath` to bundle pre-rendered widget state for the first time a widget is added to the home screen. See [Widget Pre-rendering](/android/development/widget-pre-rendering) for details. ## Example Configuration [Section titled “Example Configuration”](#example-configuration) ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "enableNotifications": true, "widgets": [ { "id": "voltra", "displayName": "Voltra Widget", "description": "Voltra logo widget", "minCellWidth": 2, "minCellHeight": 2, "targetCellWidth": 2, "targetCellHeight": 2, "resizeMode": "horizontal|vertical", "widgetCategory": "home_screen", "initialStatePath": "./widgets/android-voltra-widget-initial.tsx", "previewImage": "./assets/voltra-icon.jpg" }, { "id": "interactive_todos", "displayName": "Interactive Todos", "description": "Quick todo list widget", "targetCellWidth": 2, "targetCellHeight": 2, "previewLayout": "./assets/widgets/todos-preview.xml" } ] } ] ] } } ``` # Widget Sizing & Previews (Android) > How Android sizes widgets in grid cells and dp, and how to set the previews shown in the widget picker. ## Widget Sizing [Section titled “Widget Sizing”](#widget-sizing) ### Grid Cells vs Density-Independent Pixels (dp) [Section titled “Grid Cells vs Density-Independent Pixels (dp)”](#grid-cells-vs-density-independent-pixels-dp) Android widgets are sized two different ways depending on the OS version. Android 12+ places widgets using `targetCellWidth`/`targetCellHeight`, in grid cells. Android 11 and older don’t understand those attributes at all and place widgets using `minWidth`/`minHeight`, in dp, so Voltra always emits both. When `minWidth`/`minHeight` aren’t set explicitly, they’re derived from the widget’s cell size using Google’s published figures for a 5x4 handset grid: * **minWidth (dp) = (cellCount × 73) - 16** * **minHeight (dp) = (cellCount × 66) - 15** For example, 2 cells comes out to 130 dp wide and 117 dp tall, and 4 cells to 276 dp wide and 249 dp tall. Cell size varies by device, launcher and orientation, so this conversion is only an approximation, and it only matters on Android 11 and older — Android 12+ sizes the widget from `targetCellWidth`/ `targetCellHeight` directly. If you need precise placement on Android 11 and older, set `minWidth` and `minHeight` explicitly in dp instead of relying on the conversion. ### Standard Dimensions [Section titled “Standard Dimensions”](#standard-dimensions) | Family | Cells | Default DP | Typical Use | | ----------- | ----- | ---------- | ----------------- | | Small | 2×1 | 130 × 51 | Quick glance info | | Medium | 2×2 | 130 × 117 | Main widget size | | Large | 4×2 | 276 × 117 | Rich content | | Extra Large | 4×4 | 276 × 249 | Complex layouts | ### Resize Bounds [Section titled “Resize Bounds”](#resize-bounds) Voltra can also emit `minResizeWidth`, `minResizeHeight`, `maxResizeWidth`, and `maxResizeHeight` in the generated `appwidget-provider` XML, all optional and all in dp: * `minResizeWidth`/`minResizeHeight` set the smallest size the user can resize the widget to, and are supported on all Android versions. * `maxResizeWidth`/`maxResizeHeight` set the largest size the user can resize the widget to. They were introduced in Android 12 and are ignored on older versions. These bounds only take effect on axes the widget can resize along, per `resizeMode` — a `maxResizeHeight` on a widget with `resizeMode: "horizontal"` has no effect, for instance. Set only the ones you need; Voltra emits exactly what you provide and nothing otherwise, so existing widgets are unaffected. Android also ignores a bound that contradicts the widget’s minimum size: `minResizeWidth` has no effect if it’s greater than `minWidth`, and `maxResizeWidth` has no effect if it’s smaller than `minWidth` — likewise for the height pair against `minHeight`. Since `minWidth`/`minHeight` are often derived from `targetCellWidth`/`targetCellHeight` rather than written explicitly (see above), Voltra warns at build time when it detects one of these contradictions, naming the attribute, rather than failing the build. For example: ```json { "widgets": [ { "id": "weather", "displayName": "Weather Widget", "targetCellWidth": 2, "targetCellHeight": 2, "resizeMode": "horizontal|vertical", "minResizeWidth": 110, "minResizeHeight": 100, "maxResizeWidth": 276, "maxResizeHeight": 249 } ] } ``` This lets the widget resize down to 110×100 dp, and up to 276×249 dp on Android 12+. ## Widget Picker Previews [Section titled “Widget Picker Previews”](#widget-picker-previews) When users add a widget to their home screen, Android displays a preview in the widget picker. Voltra supports three preview methods, with automatic fallback: 1. **`previewLayout`** (Android 12+) - Custom XML layout for scalable preview 2. **`previewImage`** (All versions) - Static image or auto-generated layout 3. **Default** - System placeholder layout ### Using `previewImage` [Section titled “Using previewImage”](#using-previewimage) Static preview image for all Android versions: ```json { "widgets": [ { "id": "weather", "displayName": "Weather Widget", "targetCellWidth": 2, "targetCellHeight": 2, "previewImage": "./assets/widgets/weather-preview.png" } ] } ``` When only `previewImage` is specified, Voltra automatically generates a layout that displays the image with proper scaling. ### Using `previewLayout` [Section titled “Using previewLayout”](#using-previewlayout) Custom XML layout for scalable previews (Android 12+): ```json { "widgets": [ { "id": "todos", "displayName": "Todo Widget", "targetCellWidth": 2, "targetCellHeight": 2, "previewLayout": "./assets/widgets/todos-preview.xml" } ] } ``` **Example `todos-preview.xml`:** ```xml ``` The preview layout is rendered at the widget’s target size and displayed in the widget picker. ### Combined Preview Setup [Section titled “Combined Preview Setup”](#combined-preview-setup) For best results across Android versions, provide both: ```json { "widgets": [ { "id": "weather", "displayName": "Weather Widget", "targetCellWidth": 2, "targetCellHeight": 2, "previewImage": "./assets/widgets/weather-preview.png", "previewLayout": "./assets/widgets/weather-preview.xml", "initialStatePath": "./widgets/weather-initial.tsx" } ] } ``` This uses `previewLayout` on Android 12+, falls back to `previewImage` on Android 11 and earlier, and shows actual widget content on the home screen via `initialStatePath` once available. # Charts (Android) > Build bar, line, area, point, rule, and sector charts in Android widgets with VoltraAndroid.Chart and its mark components. Use charts in Android widgets to show trends, comparisons, progress, or composition at a glance. You can mix bars, lines, areas, points, rules, and sectors in a single chart. Caution Mark components (`BarMark`, `LineMark`, and the other mark types) must be direct children of ``. Do not wrap them in a custom component. ## Basic Usage [Section titled “Basic Usage”](#basic-usage) Wrap one or more mark components inside ``: ```tsx ``` ## Data Types [Section titled “Data Types”](#data-types) All marks except `RuleMark` take a `data` prop. There are two data shapes depending on the mark type: ```typescript // BarMark, LineMark, AreaMark, PointMark type ChartDataPoint = { x: string | number // Categorical ("Jan") or numeric (42) y: number series?: string // Optional — groups data for multi-series charts } // SectorMark type SectorDataPoint = { value: number // Proportional angular value category: string // Sector label } ``` ## Marks [Section titled “Marks”](#marks) Pick the mark that fits your data: bars for comparing values across categories, lines for trends over time, areas for volume, points for sparse or scattered measurements, rules for reference lines, and sectors for pie/donut breakdowns. ### BarMark [Section titled “BarMark”](#barmark) **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Fill color. * `cornerRadius` (number, optional): Rounded bar corners. * `width` (number, optional): Fixed bar width. * `stacking` (string, optional): `"grouped"` for side-by-side bars in a multi-series chart. ```tsx ``` *** ### LineMark [Section titled “LineMark”](#linemark) **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Line color. * `lineWidth` (number, optional): Stroke width. * `interpolation` (string, optional): `"linear"`, `"monotone"`, `"catmullRom"`, `"cardinal"`, `"stepStart"`, `"stepCenter"`, or `"stepEnd"`. ```tsx ``` *** ### AreaMark [Section titled “AreaMark”](#areamark) **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Fill color. * `interpolation` (string, optional): Same options as `LineMark`. ```tsx ``` *** ### PointMark [Section titled “PointMark”](#pointmark) **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Point color. * `symbolSize` (number, optional): Point size. ```tsx ``` *** ### RuleMark [Section titled “RuleMark”](#rulemark) A horizontal or vertical reference line. Unlike other marks, RuleMark has no `data` array. **Parameters:** * `yValue` (number, optional): Draw a horizontal line at this y value. * `xValue` (string | number, optional): Draw a vertical line at this x value. * `color` (string, optional): Line color. * `lineWidth` (number, optional): Stroke width. ```tsx ``` *** ### SectorMark [Section titled “SectorMark”](#sectormark) Pie and donut charts. **Parameters:** * `data` (SectorDataPoint\[], required): Sector data with `value` and `category`. * `color` (string, optional): Fill color (overrides automatic coloring). * `innerRadius` (number, optional): `0` = pie chart, any value above `0` = donut chart. Values ≤ 1 are treated as a ratio of the max radius; values > 1 are treated as absolute dp. * `outerRadius` (number, optional): Same behavior as `innerRadius`. * `angularInset` (number, optional): Gap between sectors in degrees. ```tsx // Pie chart // Donut chart ``` ## Chart Props [Section titled “Chart Props”](#chart-props) The `` container accepts these props in addition to the standard `style` prop: | Prop | Type | Description | | ---------------------- | -------------------------------------- | --------------------------------------- | | `xAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the x-axis | | `xAxisGridStyle` | `{ visible?: boolean }` | Show or hide x-axis grid lines | | `yAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the y-axis | | `yAxisGridStyle` | `{ visible?: boolean }` | Show or hide y-axis grid lines | | `foregroundStyleScale` | `Record` | Map series names to colors | | `yScale` | `{ min?: number; max?: number }` | Pin the y-axis lower and/or upper bound | ## Multi-Series Charts [Section titled “Multi-Series Charts”](#multi-series-charts) Add a `series` field to your data points when you want multiple datasets in the same chart. Use `foregroundStyleScale` to keep those series colors consistent: ```tsx ``` Without `foregroundStyleScale`, colors are chosen automatically. For side-by-side bars, set `stacking="grouped"`: ```tsx ``` ## Combining Marks [Section titled “Combining Marks”](#combining-marks) Mix mark types when one chart needs both context and emphasis, such as bars for totals plus a rule for a target: ```tsx ``` ## Value Range [Section titled “Value Range”](#value-range) The y-axis frames the values a chart is given: * `LineMark` and `PointMark` scale to the data range, so a series that varies within a narrow band — exchange rates, ratios, temperatures — fills the plot instead of flattening against the top edge. Axis labels carry as many decimals as the distance between ticks needs. * `BarMark` and `AreaMark` keep zero on the axis, because their height is read against the baseline. * `RuleMark` values count as part of the range, so a reference line always stays in view. Data that nearly reaches zero keeps zero on the axis either way, so a series sitting just above the baseline is not exaggerated. Use `yScale` when a chart needs a fixed window rather than one that follows the data: ```tsx ``` Either bound can stand alone: `yScale={{ min: 0 }}` keeps the baseline at zero and lets the top follow the data. A pinned bound wins over the rules above, including the zero baseline bars and areas otherwise keep, and values outside the pinned range are clipped to the plot. ## Sizing [Section titled “Sizing”](#sizing) Chart dimensions are read from the `style` prop: * **Fixed size**: `style={{ width: 300, height: 200 }}` * **Fill parent**: `style={{ width: '100%', height: '100%' }}` If no width or height is specified, the chart defaults to 300×200 dp. ## Platform Notes [Section titled “Platform Notes”](#platform-notes) * `legendVisibility` is not currently available on Android charts. * Point markers are circular on Android. * `innerRadius` and `outerRadius` on `SectorMark` accept either a ratio (`0` to `1`) or a larger fixed value. # Interactive Controls (Android) > Reference for Voltra Android interactive components such as Button, Switch, and CheckBox, and how clicks open the app. User interface controls that respond to user interaction on Android widgets. Note On Android, buttons, toggles, checkboxes, and radio buttons always open the application when clicked. You can provide a `deepLinkUrl` to open a specific screen instead of the main activity. ### Button [Section titled “Button”](#button) Standard button component. **Parameters:** * `enabled` (boolean, optional): Whether the button is enabled. * `deepLinkUrl` (string, optional): URL to open when the button is clicked. If not provided, the app will open to its main activity. Voltra also provides specialized button variants: #### FilledButton [Section titled “FilledButton”](#filledbutton) * `text` (string): Button label. * `enabled` (boolean, optional). * `deepLinkUrl` (string, optional). * `icon` (object, optional): `{ assetName: string }`. * `backgroundColor` (string, optional). * `contentColor` (string, optional). * `maxLines` (number, optional). #### OutlineButton [Section titled “OutlineButton”](#outlinebutton) * `text` (string): Button label. * `enabled` (boolean, optional). * `deepLinkUrl` (string, optional). * `icon` (object, optional): `{ assetName: string }`. * `contentColor` (string, optional). * `maxLines` (number, optional). #### CircleIconButton & SquareIconButton [Section titled “CircleIconButton & SquareIconButton”](#circleiconbutton--squareiconbutton) * `enabled` (boolean, optional). * `deepLinkUrl` (string, optional). * `icon` (object, optional): `{ assetName: string, base64: string }`. * `contentDescription` (string, optional). * `backgroundColor` (string, optional). * `contentColor` (string, optional). *** ### Clickable Components [Section titled “Clickable Components”](#clickable-components) Most components support being clickable by setting the `pressable` prop (short name `prs` in raw elements) in their props. **Parameters:** * `pressable` (boolean): Set to `true` to make the component respond to clicks. * `deepLinkUrl` (string, optional): URL to open when clicked. *** ### Switch [Section titled “Switch”](#switch) A toggle switch component. **Parameters:** * `id` (string): Unique identifier for interaction events. * `checked` (boolean, optional): Current state of the switch. * `deepLinkUrl` (string, optional): URL to open when clicked. * `text` (string, optional): Label displayed next to the switch. * `thumbCheckedColor` (string, optional). * `thumbUncheckedColor` (string, optional). * `trackCheckedColor` (string, optional). * `trackUncheckedColor` (string, optional). * `maxLines` (number, optional): Maximum lines for the label. *** ### CheckBox [Section titled “CheckBox”](#checkbox) Standard checkbox component. **Parameters:** * `id` (string): Unique identifier for interaction events. * `checked` (boolean, optional). * `deepLinkUrl` (string, optional). * `text` (string, optional). * `checkedColor` (string, optional). * `uncheckedColor` (string, optional). * `maxLines` (number, optional). *** ### RadioButton [Section titled “RadioButton”](#radiobutton) Standard radio button component. **Parameters:** * `id` (string): Unique identifier for interaction events. * `checked` (boolean, optional). * `enabled` (boolean, optional). * `deepLinkUrl` (string, optional). * `text` (string, optional). * `checkedColor` (string, optional). * `uncheckedColor` (string, optional). * `maxLines` (number, optional). # Layout & Containers (Android) > Reference for Voltra Android layout components built on Jetpack Compose Glance, such as Column, Row, and Box, and their Glance limits. Components that arrange other elements or provide structural grouping using Jetpack Compose Glance primitives. See [Styling](/android/development/styling) for details on layout and spacing properties. ### Column [Section titled “Column”](#column) A vertical container that arranges its children in a column. Glance limit `Column` supports at most 10 direct rendered children. Jetpack Glance truncates extra children. Use `LazyColumn` for dynamic or scrollable collections. **Parameters:** * `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`. * `verticalAlignment` (string, optional): `"top"`, `"center-vertically"`, `"bottom"`. *** ### Row [Section titled “Row”](#row) A horizontal container that arranges its children in a row. Glance limit `Row` supports at most 10 direct rendered children. Jetpack Glance truncates extra children. Use `LazyColumn` for dynamic or scrollable collections. **Parameters:** * `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`. * `verticalAlignment` (string, optional): `"top"`, `"center-vertically"`, `"bottom"`. *** ### Box [Section titled “Box”](#box) A container that stacks its children on top of each other. **Parameters:** * `contentAlignment` (string, optional): Combined alignment. Supports `"top-start"`, `"top-center"`, `"top-end"`, `"center-start"`, `"center"`, `"center-end"`, `"bottom-start"`, `"bottom-center"`, `"bottom-end"`. *** ### Scaffold [Section titled “Scaffold”](#scaffold) A top-level container that provides a standard layout structure for widgets. **Parameters:** * `backgroundColor` (string, optional): Background color for the scaffold. * `horizontalPadding` (number, optional): Horizontal padding in dp. *** ### TitleBar [Section titled “TitleBar”](#titlebar) A component that displays a title bar with a required leading icon. **Parameters:** * `title` (string): Title text to display. * `startIcon` (object, required): `{ assetName: string }` or `{ base64: string }`. * `textColor` (string, optional). * `iconColor` (string, optional). * `fontFamily` (string, optional): `"monospace"`, `"serif"`, `"sans-serif"`, or `"cursive"`. *** ### Spacer [Section titled “Spacer”](#spacer) A component that provides fixed spacing between elements. **Parameters:** * `size` (number): Size of the spacer in dp. *** ### LazyColumn [Section titled “LazyColumn”](#lazycolumn) A scrollable vertical list that only renders visible items. **Parameters:** * `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`. *** ### LazyVerticalGrid [Section titled “LazyVerticalGrid”](#lazyverticalgrid) A scrollable grid of items. **Parameters:** * `columns` (number | `"adaptive"`): Number of columns or `"adaptive"` for an adaptive grid. * `minSize` (number, optional): Minimum size (in dp) for items in adaptive grid mode. * `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`. * `verticalAlignment` (string, optional): `"top"`, `"center"`, `"bottom"`. # Data Visualization & Status (Android) > Reference for Voltra Android components that show data and progress, including LinearProgressIndicator and its limits. Components for displaying data and status information on Android widgets. ### LinearProgressIndicator [Section titled “LinearProgressIndicator”](#linearprogressindicator) A horizontal progress bar. **Parameters:** * `progress` (number, optional): Current progress value (0.0 to 1.0). If omitted, the indicator will be indeterminate. * `color` (string, optional): Color for the progress indicator. * `backgroundColor` (string, optional): Color for the background track. *** ### CircularProgressIndicator [Section titled “CircularProgressIndicator”](#circularprogressindicator) A circular progress indicator. **Parameters:** * `color` (string, optional): Color for the progress indicator. Indeterminate Only Due to Jetpack Compose Glance limitations, the `CircularProgressIndicator` on Android renders in **indeterminate** mode. *** ### ArcProgressIndicator [Section titled “ArcProgressIndicator”](#arcprogressindicator) A determinate arc gauge: a partial ring whose stroke fills clockwise, with rounded ends and a gap at the bottom by default. Children are centered on top of the arc, so a label, an icon, or nothing goes in the middle. **Parameters:** * `progress` (number, optional): Fill fraction, clamped to 0.0–1.0. Defaults to `0`. * `color` (string, optional): Stroke color of the filled arc. Defaults to the widget theme’s progress color. * `trackColor` (string, optional): Stroke color of the unfilled arc. Defaults to the widget theme’s track color; use `transparent` to hide the track. * `strokeWidth` (number, optional): Stroke width in dp of both arcs. Defaults to `8`. * `startAngle` (number, optional): Angle in degrees where the arc begins. `0` is 3 o’clock and positive is clockwise. Defaults to `135`. * `sweepAngle` (number, optional): Total angular length of the track in degrees. `360` makes a closed ring. Defaults to `270`. * `lineCap` (`'round' | 'butt'`, optional): End shape of both arcs. Defaults to `'round'`. * `gradientColors` (string\[], optional): Sweep gradient spread across the track, starting at `startAngle`. Overrides `color`. Needs at least two colors; a single color is drawn as a solid stroke, and the gradient is ignored if any color fails to parse. ```tsx 75% ``` Unlike the other two indicators, this one works on every supported Android version, because it is drawn as a bitmap rather than composed from a Glance progress primitive. Give the component a width and a height. When you leave an axis unsized it falls back to 64 dp, which is rarely what you want, and when you give it a `flex` weight the parent controls both axes, so size the arc through the parent instead. Because the arc occupies one of the ten child slots a Glance `Box` allows, you can nest at most nine elements inside it. Bitmap Memory The arc is a bitmap, so it costs memory that grows with the square of its pixel size. Voltra sizes it from the smaller of the component’s width and height, multiplies by the display density clamped to 1–3.5, and caps each edge at 512 px, so one gauge costs at most 1 MiB and a typical one around a quarter of that. Identical gauges share a single bitmap, so a fixed-size gauge costs its bytes once per widget no matter how many responsive size variants it appears in; a gauge sized with `'100%'` resolves to a different bitmap per variant. The system caps the bitmaps of one widget instance at roughly 1.5 screens’ worth of pixels, so very large or very many arcs in a single widget remain your responsibility. The indicator does not animate. Changing `progress` redraws it. # Visual Elements & Typography (Android) > Reference for Voltra Android visual components such as Text and Image that display static content in widgets. Static or decorative elements used to display content on Android widgets. See [Styling](/android/development/styling) for details on supported style properties. ### Text [Section titled “Text”](#text) Displays text content. **Parameters:** * `maxLines` (number, optional): Maximum number of lines to display. * `renderAsBitmap` (boolean, optional): Renders text as a bitmap image to enable [custom fonts](/android/development/custom-fonts). Requires `fontFamily` in the style prop. *** ### Image [Section titled “Image”](#image) Displays bitmap images from the asset catalog, preloaded runtime cache, or base64 encoded data. SVGs should be rasterized through the image preloading API and referenced by `assetName`. **Parameters:** * `source` (object, optional): Image source object. * `assetName` (string): Reference to a pre-bundled image (drawable resource) or a [preloaded image](/android/development/image-preloading). * `base64` (string): Base64 encoded image data. * `resizeMode` (string, optional): `"cover"`, `"contain"`, `"stretch"`, `"repeat"`, or `"center"`. * `contentDescription` (string, optional): Accessibility description for the image. * `contentScale` (string, optional): Glance-specific scaling mode: `"crop"`, `"cover"`, `"fit"`, `"contain"`, `"fill-bounds"`, or `"stretch"`. * `alpha` (number, optional): Opacity value from 0.0 to 1.0. * `colorFilter` (string, optional): Color tint filter for the image. * `tintColor` (string, optional): Legacy alias for `colorFilter`. * `fallback` (ReactNode, optional): Custom content rendered when the image is missing. **Styling the fallback:** To add a background color when an image is missing, use `backgroundColor` in the `style` prop: ```jsx ``` Image Preloading For dynamic images from remote URLs, use the [Image Preloading](/android/development/image-preloading) API to cache them locally for use in widgets. # Custom Fonts > Use custom fonts in Android widgets by rendering text as a bitmap with a Typeface loaded from the fonts you list in the plugin config. Android Glance only supports a handful of built-in font families (`monospace`, `serif`, `sans-serif`, `cursive`). Voltra works around this by rendering text as a bitmap with a custom `Typeface` loaded from `assets/fonts/`. ## Setup [Section titled “Setup”](#setup) ### 1. Add font files to the plugin config [Section titled “1. Add font files to the plugin config”](#1-add-font-files-to-the-plugin-config) List your font paths in the top-level `fonts` array. These can be local files or packages from `@expo-google-fonts`: ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "fonts": [ "node_modules/@expo-google-fonts/pacifico/400Regular/Pacifico_400Regular.ttf", "./assets/fonts/MyCustomFont.ttf" ], "widgets": [] } ] ] } } ``` ### 2. Run prebuild [Section titled “2. Run prebuild”](#2-run-prebuild) ```bash npx expo prebuild ``` The plugin copies each font file to `android/app/src/main/assets/fonts/` automatically. ### 3. Use `renderAsBitmap` on Text [Section titled “3. Use renderAsBitmap on Text”](#3-use-renderasbitmap-on-text) ```tsx import { VoltraAndroid } from '@use-voltra/android' Hello Voltra! ``` The `fontFamily` value should match the font filename **without the extension**. Note that `renderAsBitmap` text is rasterized — it won’t respond to system font size or accessibility settings. Use it only when a custom typeface is needed. ## Supported style properties [Section titled “Supported style properties”](#supported-style-properties) When rendering as bitmap, the following text style properties are supported: | Property | Description | | -------------------- | ------------------------------------------ | | `fontSize` | Font size in sp (scaled to device density) | | `fontFamily` | Font filename without extension | | `fontWeight` | `"normal"` or `"bold"` | | `color` | Text color | | `textAlign` | `"left"`, `"center"`, `"right"` | | `textDecorationLine` | `"underline"`, `"line-through"` | | `letterSpacing` | Letter spacing value | | `lineHeight` | Line spacing | ## Built-in font families [Section titled “Built-in font families”](#built-in-font-families) For built-in families you don’t need `renderAsBitmap` — use `fontFamily` in style directly: * `monospace` * `serif` * `sans-serif` * `cursive` These are passed through to Glance’s native `FontFamily` API. # Developing Android Widgets > Build Android Home Screen widgets from JSX with the Glance primitives Voltra maps to, plus links to the related development guides. Voltra allows you to build Android Home Screen widgets using JSX and Jetpack Compose Glance primitives. ## Glance Primitives [Section titled “Glance Primitives”](#glance-primitives) On Android, you use `VoltraAndroid` components which map to Glance primitives: * **Column:** Vertical layout * **Row:** Horizontal layout * **Box:** Stacked layout * **Spacer:** Flexible spacing * **Text:** Displaying text * **Image:** Displaying images * **Scaffold:** Top-level container ### Example Widget [Section titled “Example Widget”](#example-widget) ```tsx import { VoltraAndroid } from '@use-voltra/android' const WeatherWidget = ({ temperature, condition }) => ( {temperature}°C {condition} ) ``` ## Update API [Section titled “Update API”](#update-api) To update a widget’s content, use the `updateAndroidWidget` function from `@use-voltra/android-client`: ```typescript import { updateAndroidWidget } from '@use-voltra/android-client' await updateAndroidWidget('weather_widget', ) ``` `updateAndroidWidget` only updates payload-driven widgets like this one. Calling it on a Dynamic Widget (see [Dynamic Widgets](/android/development/dynamic-widgets)) rejects with `VOLTRA_WIDGET_KIND_MISMATCH`. ## Layout Constraints [Section titled “Layout Constraints”](#layout-constraints) Unlike standard React Native or iOS Stacks, Android Glance layouts are more restrictive: * **Width/Height:** Use fixed numbers (dp), `"100%"` to fill available space, or `"auto"` to wrap content. * **Modifiers:** Most styling is handled via the `style` prop, which maps to Glance `Modifier`s. See [Styling](/android/development/styling) for full details. * **Alignment:** Use `verticalAlignment` and `horizontalAlignment` props on `Column` and `Row`. ## Advanced Features [Section titled “Advanced Features”](#advanced-features) * **[Querying Active Widgets](/android/development/querying-active-widgets):** Detect active widget instances and their sizes. * **[Testing and Previews](/android/development/testing-and-previews):** Preview layouts within your app. * **[Widget Picker Previews](/android/api/widget-sizing-and-previews):** Configure how your widget appears in the Android widget picker. * **[Image Preloading](/android/development/image-preloading):** Cache remote images for use in widgets. * **[Widget Pre-rendering](/android/development/widget-pre-rendering):** Provide initial state for widgets before the app first runs. # Dynamic colors > Use AndroidDynamicColors semantic tokens so widgets follow the Material palette and wallpaper changes without a JavaScript re-render. Voltra supports Android dynamic colors through semantic tokens exposed from `@use-voltra/android`. These colors follow the current Android Material palette, so widgets can pick up wallpaper and theme changes without waiting for JavaScript to run again. ## Importing dynamic colors [Section titled “Importing dynamic colors”](#importing-dynamic-colors) ```tsx import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android' ``` `AndroidDynamicColors` includes these roles: * `primary` * `onPrimary` * `primaryContainer` * `onPrimaryContainer` * `secondary` * `onSecondary` * `secondaryContainer` * `onSecondaryContainer` * `tertiary` * `onTertiary` * `tertiaryContainer` * `onTertiaryContainer` * `error` * `errorContainer` * `onError` * `onErrorContainer` * `background` * `onBackground` * `surface` * `onSurface` * `surfaceVariant` * `onSurfaceVariant` * `outline` * `inverseOnSurface` * `inverseSurface` * `inversePrimary` * `widgetBackground` ## Example [Section titled “Example”](#example) ```tsx import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android' export function WeatherWidget() { return ( 21° ) } ``` ## Where you can use them [Section titled “Where you can use them”](#where-you-can-use-them) You can use `AndroidDynamicColors.*` anywhere Android accepts a color value, including: * `style.backgroundColor` * `style.color` * `Image.colorFilter` * button `backgroundColor` and `contentColor` * `TitleBar.textColor` and `TitleBar.iconColor` * switch, checkbox, and radio button colors * progress indicator colors * chart mark colors ## Server-driven widgets [Section titled “Server-driven widgets”](#server-driven-widgets) Dynamic color tokens work in server-rendered Android widgets too. ```tsx import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android' const content = ( Server-rendered widget ) ``` The same `AndroidDynamicColors.*` values work whether the widget is rendered in-app or returned from your server. # Dynamic Widgets > Write Android widgets whose entry component renders on the device and reacts to app-supplied props and device state such as locale and color scheme. Dynamic Widgets run their entry component on-device and can react to both app-supplied runtime props and current device state. Declare a Dynamic Widget in `app.json` with a stable `id` and an explicit `entry`, then default-export the Dynamic Widget from that file. Your Dynamic Widget can react to: * `env.widgetFamily` * `env.colorScheme` * `env.locale`, `env.preferredLanguages`, `env.hourCycle`, `env.timeZone` and the other [locale fields](/android/development/localization) * `env.configuration` * `AndroidDynamicColors` tokens, which resolve to the current Material You palette natively When you change `app.json`, run Expo Prebuild or Voltra Apply so the updated Dynamic Widget configuration is available on device. If you change only the Dynamic Widget JS, reopen the app in development and the Dynamic Widget updates automatically. ## Set up Metro [Section titled “Set up Metro”](#set-up-metro) Dynamic Widgets require `@use-voltra/metro` in the app project. Install it alongside the Android packages: ```sh npm install @use-voltra/metro ``` Wrap the app’s existing Metro config with `withVoltra`: metro.config.js ```js const { getDefaultConfig } = require('expo/metro-config') const { withVoltra } = require('@use-voltra/metro') const config = getDefaultConfig(__dirname) module.exports = withVoltra(config) ``` ## How to use it [Section titled “How to use it”](#how-to-use-it) 1. Add an Android Dynamic Widget declaration to `app.json` with an `id`, an `entry`, and any Dynamic Widget metadata you need. 2. Default-export the Dynamic Widget function or component from the module named by `entry`. 3. Use `initialStatePath` if you want a pre-rendered first view. 4. Re-run Expo Prebuild or Voltra Apply after updating `app.json`. 5. Keep Android and iOS Dynamic Widget declarations separate; the same `id` can exist on both platforms because each platform is configured separately. widgets/android/inbox-widget.tsx ```tsx import { AndroidDynamicColors, VoltraAndroid, type WidgetEnvironment } from '@use-voltra/android' type InboxDynamicWidgetProps = { // Optional because the Dynamic Widget receives {} before its first runtime props update. unreadCount?: number } type InboxDynamicWidgetConfiguration = { label?: string } export default function InboxDynamicWidget( props: InboxDynamicWidgetProps = {}, env: WidgetEnvironment = {} as WidgetEnvironment ) { const unreadCount = props.unreadCount ?? 0 const label = env.configuration?.label ?? 'Inbox' // Format with the user's locale, 12/24-hour setting and time zone. const renderedAt = (env.date ? new Date(env.date) : new Date()).toLocaleTimeString(env.locale, { hour: '2-digit', minute: '2-digit', hourCycle: env.hourCycle, timeZone: env.timeZone, }) return ( {label} {unreadCount} unread Size: {env.widgetFamily} Scheme: {env.colorScheme ?? 'light'} Rendered: {renderedAt} ) } ``` Example plugin config: ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "widgets": [ { "id": "inbox_widget", "entry": "./widgets/android/inbox-widget.tsx", "displayName": "Inbox Widget", "description": "A Dynamic Widget with runtime props and live device state", "targetCellWidth": 2, "targetCellHeight": 2, "initialStatePath": "./widgets/android/inbox-widget.tsx", "appIntent": { "parameters": [ { "name": "label", "title": "Label", "default": "Inbox" } ] } } ] } ] ] } } ``` After changing the plugin configuration, rebuild the native Android app. You also need a native rebuild after upgrading to a version of `@use-voltra/android-client` that introduces a new native API. ## Update Dynamic Widget props [Section titled “Update Dynamic Widget props”](#update-dynamic-widget-props) Call `updateAndroidDynamicWidget` from your app. The object is serialized, persisted, and passed as the first argument to the entry component on each subsequent render. The update re-renders every installed instance with the matching Dynamic Widget id. ```ts import { updateAndroidDynamicWidget } from '@use-voltra/android-client' await updateAndroidDynamicWidget('inbox_widget', { unreadCount: 7, }) ``` Dynamic Widget props must be JSON-serializable. You can use strings, numbers, booleans, `null`, arrays, and nested objects. Functions, `undefined`, `Date`, `BigInt`, and cyclic references are not supported. Before the first call to `updateAndroidDynamicWidget`, the entry component receives `{}`. The latest props object is persisted by Dynamic Widget id, survives app process restarts, and is reused until a later call replaces it or the app’s data is cleared. Choose the API by widget type `updateAndroidDynamicWidget` updates an entry-based Dynamic Widget by passing runtime props to its entry component. The legacy `updateAndroidWidget` API sends pre-rendered variant payloads to a payload-driven widget and cannot update an entry-based Dynamic Widget. Calling it on a Dynamic Widget now rejects with `VOLTRA_WIDGET_KIND_MISMATCH`, and `updateAndroidDynamicWidget` rejects the same way when called on a payload-driven widget. ## Fetching props from a server [Section titled “Fetching props from a server”](#fetching-props-from-a-server) Props do not have to come from the app. Add a `serverUpdate` alongside `entry` and the widget fetches a JSON object on a schedule and renders it, without the app running: ```json { "id": "portfolio", "entry": "./widgets/android/portfolio.tsx", "serverUpdate": { "url": "https://api.example.com/widgets/portfolio", "intervalMinutes": 30 } } ``` The response object becomes the same first argument `updateAndroidDynamicWidget` passes, so the entry component does not change. Because the server returns data rather than a rendered payload, the backend can be written in any language. `updateAndroidDynamicWidget` keeps working on a server-driven widget — the next fetch simply overwrites what you wrote. See [Server-driven widgets](/android/development/server-driven-widgets) for the response contract, the `env.serverUpdate` fields, and how to take a widget over. ## Configure each placed widget separately [Section titled “Configure each placed widget separately”](#configure-each-placed-widget-separately) Every widget placed on the Home Screen has its own `appWidgetId`. Give one placement its own values and it renders them alone — the usual reason to place a widget twice, like one weather widget on London and another on New York. The widget code does not change: it still reads `env.configuration`, and now gets the values of the placement being drawn. Three layers feed `env.configuration`, each hiding the same key in the one below it: ```plaintext defaults (app.json) < widget-type values < instance values → env.configuration ``` Read the placements, then write to one of them: ```typescript import { getActiveWidgets, setWidgetInstanceConfiguration, getWidgetInstanceConfiguration, clearWidgetInstanceConfiguration, } from '@use-voltra/android-client' const placements = await getActiveWidgets() const weather = placements.filter(widget => widget.widgetType === 'weather') if (weather.length > 0) { // One key at a time… await setWidgetInstanceConfiguration(weather[0].appWidgetId, 'city', 'London') // What this placement renders with, all three layers merged. const values = await getWidgetInstanceConfiguration(weather[0].appWidgetId) // Drop this placement's own values so it follows the widget-type ones again. await clearWidgetInstanceConfiguration(weather[0].appWidgetId) } if (weather.length > 1) { // Several keys at once, which costs one write and one re-render. await setWidgetInstanceConfiguration(weather[1].appWidgetId, { city: 'New York', units: 'fahrenheit', }) } ``` Values are strings, and only that placement re-renders. ### How the layers interact [Section titled “How the layers interact”](#how-the-layers-interact) `setWidgetConfiguration(widgetId, key, value)` still writes the widget-type value, which is what every placement without its own value for that key renders. A placement that has its own value keeps showing it, so a later type-level write does not visibly change it. `clearWidgetInstanceConfiguration` drops the placement’s values and it follows the type-level ones again. `getWidgetConfiguration(widgetId)` reads the type-level layer — the defaults plus any type-level values — without any placement’s own values. ### What happens to the values [Section titled “What happens to the values”](#what-happens-to-the-values) Removing a widget from the Home Screen drops that placement’s values, so adding the widget again starts from the widget-type values rather than inheriting the old placement’s. When the launcher restores its layout from a backup and assigns new ids, each placement’s values move with it, so a configured widget survives a device restore. These APIs reject when the `appWidgetId` is not a placement of one of your own Dynamic Widgets: `VOLTRA_WIDGET_INSTANCE_NOT_FOUND` when nothing of yours is placed with that id, `VOLTRA_WIDGET_KIND_MISMATCH` when the placement is a payload-driven widget, and `VOLTRA_WIDGET_NOT_FOUND` when the widget id cannot be resolved. Nothing is stored unless the call succeeds. ### Platform differences [Section titled “Platform differences”](#platform-differences) The Home Screen’s own edit gesture does not open a Voltra configuration screen yet, so your app is the only place to change a placement’s values on Android. On iOS the system Edit Widget sheet writes them instead, generated from the same `appIntent.parameters`, and the widget reads `env.configuration` exactly as it does here. ## Runtime props and configuration are separate [Section titled “Runtime props and configuration are separate”](#runtime-props-and-configuration-are-separate) Dynamic Widget props are app-owned state passed as the entry component’s first argument. Configuration values are declared through `appIntent.parameters`, updated in-app with `setWidgetConfiguration` for every placement or `setWidgetInstanceConfiguration` for one, and read from `env.configuration`. Updating one does not replace the other. ## Localization [Section titled “Localization”](#localization) Pass `env.locale` and `env.hourCycle` to every `Intl` and `toLocale*` call, and pick a translation with `resolveLocale(env, messages)`. `Intl.PluralRules`, `Intl.RelativeTimeFormat`, `Intl.ListFormat` and `Intl.DisplayNames` are not available in Android widgets unless you add the polyfills. See [Localization](/android/development/localization) for the polyfills, every locale field, and how to let the app choose the widget language. ## Notes [Section titled “Notes”](#notes) * There is no `export` field in app.json for Dynamic Widgets. * The default-exported Dynamic Widget function or component name does not need to match the widget `id`. * Use a real device to verify release rendering. * `initialStatePath` gives the Dynamic Widget a pre-rendered first view. * To use Glance modifiers that `style` does not cover, such as `semantics` or `appWidgetBackground`, see [Native modifiers](/android/development/native-modifiers). # Image Preloading (Android) > API reference for downloading remote images into the app cache so Android widgets can display them through assetName. Android widgets have limitations when it comes to displaying remote images directly. The image preloading API allows you to download images to the app’s cache directory, making them available to your widgets via a local `FileProvider`. ## Overview [Section titled “Overview”](#overview) The image preloading system on Android works by: 1. Downloading images from URLs to the internal app cache. 2. Rasterizing SVG inputs to PNG when needed. 3. Making these images available to Voltra widgets via the `assetName` property. 4. Providing APIs to reload widgets when new images are ready. ## API Reference [Section titled “API Reference”](#api-reference) ### `preloadImages(images: PreloadImageOptions[]): Promise` [Section titled “preloadImages(images: PreloadImageOptions\[\]): Promise\”](#preloadimagesimages-preloadimageoptions-promisepreloadimagesresult) Downloads images to the Android cache for use in Widgets. Each item must be either a URL preload (`url`) or an SVG preload (`svg`). The TypeScript types express this as a union of two variants: ```typescript type PreloadImageUrlOptions = { key: string // The assetName to use when referencing this image url: string // URL to download the image from method?: 'GET' | 'POST' | 'PUT' // HTTP method (default: 'GET') headers?: Record // Optional HTTP headers width?: number height?: number } type PreloadImageSvgOptions = { key: string // The assetName to use when referencing this image svg: string // Inline SVG markup to rasterize and cache as PNG width?: number // Typically required for SVG rasterization (see native errors if omitted) height?: number } type PreloadImageOptions = PreloadImageUrlOptions | PreloadImageSvgOptions type PreloadImageFailure = { key: string error: string } type PreloadImagesResult = { succeeded: string[] // Keys of successfully downloaded images failed: PreloadImageFailure[] // Failed downloads with error messages } ``` **Example:** ```typescript import { preloadImages } from '@use-voltra/android-client' const result = await preloadImages([ { url: 'https://example.com/album-art.jpg', key: 'current-album', headers: { Authorization: 'Bearer token' }, }, { key: 'status-icon-active', svg: '', width: 24, height: 24, }, ]) if (result.succeeded.includes('status-icon-active')) { // Images are ready to be used in widgets } ``` ### `reloadWidgets(widgetIds?: string[]): Promise` [Section titled “reloadWidgets(widgetIds?: string\[\]): Promise\”](#reloadwidgetswidgetids-string-promisevoid) Reloads Android widgets to pick up newly preloaded images. If no `widgetIds` are provided, all active widgets will be reloaded. ```typescript import { reloadWidgets } from '@use-voltra/android-client' // Reload all widgets await reloadWidgets() // Reload specific widgets await reloadWidgets(['weather_widget']) ``` ### `clearPreloadedImages(keys?: string[]): Promise` [Section titled “clearPreloadedImages(keys?: string\[\]): Promise\”](#clearpreloadedimageskeys-string-promisevoid) Removes preloaded images from the Android cache. If no `keys` are provided, all preloaded images will be cleared. ```typescript import { clearPreloadedImages } from '@use-voltra/android-client' // Clear specific images await clearPreloadedImages(['current-album']) // Clear all preloaded images await clearPreloadedImages() ``` ## Usage in Android Widgets [Section titled “Usage in Android Widgets”](#usage-in-android-widgets) Once images are preloaded, reference them using the `assetName` property in the `VoltraAndroid.Image` component: ```tsx import { VoltraAndroid } from '@use-voltra/android' function MusicWidget({ albumKey }) { return ( ) } ``` # Images > Compare the three ways to include images in Android widgets: build-time asset copying, runtime preloading, and Base64 encoding. Voltra provides three different approaches for including images in your Android widgets, each with different trade-offs and use cases: * **Build-time asset copying**: Best for static icons and assets known at build time * **Runtime preloading**: Best for dynamic images from remote URLs * **Base64 encoding**: Best for small, generated images ## Build-time asset copying [Section titled “Build-time asset copying”](#build-time-asset-copying) Place images in the `/assets/voltra-android/` directory and they’ll be automatically processed and copied to the Android drawable resources during build. ```plaintext project-root/ ├── assets/ │ └── voltra-android/ │ ├── logo.png │ ├── weather/ │ │ ├── sunny.svg │ │ └── rainy.xml │ └── background.webp ``` Run `npx expo prebuild` to apply changes — images are detected during the build, sanitized to fit Android resource naming rules, and copied into the native Android project (SVGs are converted to Vector Drawables along the way). ### Naming & Sanitization [Section titled “Naming & Sanitization”](#naming--sanitization) Android drawable resources have strict naming conventions. Voltra automatically handles this for you: * **Sanitization:** Uppercase letters are converted to lowercase. Hyphens and other special characters are replaced with underscores. * **Flattening:** Subdirectories are flattened into the resource name to avoid conflicts. **Examples:** | Source File | Android Resource Name | | ----------------------------------------- | --------------------- | | `assets/voltra-android/Logo.png` | `logo` | | `assets/voltra-android/icons/My-Icon.png` | `icons_my_icon` | | `assets/voltra-android/weather/sunny.svg` | `weather_sunny` | ### Supported Formats [Section titled “Supported Formats”](#supported-formats) * **Bitmap:** `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp` * **Vector:** `.svg` (converted to Vector Drawable), `.xml` (native Vector Drawable) ### Usage [Section titled “Usage”](#usage) Reference these images using their sanitized name in the `assetName` property. You do not need to include the file extension. ```tsx import { VoltraAndroid } from '@use-voltra/android' // assets/voltra-android/logo.png -> "logo" // assets/voltra-android/weather/sunny.svg -> "weather_sunny" ``` ## Runtime preloading [Section titled “Runtime preloading”](#runtime-preloading) For dynamic images from remote URLs, use Voltra’s image preloading API to cache images locally. See [Image Preloading](/android/development/image-preloading) for how it works. Once images are preloaded, reference them using the key you provided: ```tsx import { VoltraAndroid } from '@use-voltra/android' function ProfileWidget({ user }) { return ( {user.name} ) } ``` For detailed API documentation, see [Image Preloading](/android/development/image-preloading). ## Base64 encoding [Section titled “Base64 encoding”](#base64-encoding) You can also embed images directly as base64-encoded strings. This is useful for small, generated images or when you want to avoid file management for very simple assets. ```tsx ``` ## Comparison table [Section titled “Comparison table”](#comparison-table) | Approach | When Known | Dynamic | Setup Required | Performance | | -------------- | ------------- | ------- | ---------------- | -------------------------------- | | **Build-time** | Build time | No | File placement | Best (Native Resource) | | **Preloading** | Runtime | Yes | Preload API call | Good (Cached File) | | **Base64** | Runtime/Build | No | None | Fair (Memory intensive if large) | # Localization > Translate Android Dynamic Widgets, format dates and numbers from env, and localize the widget picker name and description. A Dynamic Widget renders on the device, so your JavaScript can translate the widget and format dates, numbers and units for the person looking at it. Every render receives the language and regional settings on `env`, and placed widgets render again when those settings change. ## What the widget knows about the user [Section titled “What the widget knows about the user”](#what-the-widget-knows-about-the-user) | Field | Example | What it tells you | | -------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------- | | `locale` | `"pl-PL"` | The language and region the widget is drawn in, as a BCP-47 tag. Pass it to every `Intl` and `toLocale*` call. | | `preferredLanguages` | `["pl-PL", "en-US"]` | The user’s languages in order. A per-app language (Android 13 and newer) comes first, then the system languages. | | `appLocale` | `"pl"` | The language your app chose with `setDynamicWidgetLocale`. Absent unless you set one. | | `layoutDirection` | `"ltr"` | `"rtl"` for Arabic, Hebrew and other right-to-left languages. | | `hourCycle` | `"h23"` | `"h12"` or `"h23"`, matching the user’s 24-hour time setting. | | `timeZone` | `"Europe/Warsaw"` | The device time zone. | | `measurementSystem` | `"metric"` | `"metric"`, `"us"` or `"uk"`. Absent on Android 8 and older. | | `calendar` | `"gregory"` | The user’s calendar, spelled the way `Intl` expects. | | `firstDayOfWeek` | `2` | `1` is Sunday, `2` is Monday, up to `7` for Saturday. | Placed widgets render again after the device language, the app’s per-app language or the regional preferences change, even when the app is not running. A language change your app makes while it is running takes effect at once. If the user force-stopped the app in Settings, its widgets keep the old language until the app runs again. ## Translate widget content [Section titled “Translate widget content”](#translate-widget-content) Keep one messages object per language and let `resolveLocale` choose. It tries `appLocale`, then each entry of `preferredLanguages` (exact tag, then language only), then `locale`. If none match, it returns `en`, then `__default`, then the alphabetically first key. It returns `undefined` only when the object is empty. ```tsx import { resolveLocale, VoltraAndroid, type WidgetEnvironment } from '@use-voltra/android' const messages = { en: { title: 'Next train' }, pl: { title: 'Następny pociąg' }, } export default function TrainWidget(props: { departure?: number }, env: WidgetEnvironment) { const t = messages[resolveLocale(env, messages) ?? 'en'] const time = new Intl.DateTimeFormat(env.locale, { hour: 'numeric', minute: '2-digit', hourCycle: env.hourCycle, timeZone: env.timeZone, }).format(new Date(props.departure ?? env.date.valueOf())) return ( {t.title} {time} ) } ``` `pickLocalizedValue(map, languages)` applies the same fallback to any locale-keyed map when you want to pass the language list yourself. ## Format dates, numbers and units [Section titled “Format dates, numbers and units”](#format-dates-numbers-and-units) Pass `env.locale` to every `Intl` and `toLocale*` call, `env.timeZone` whenever you format a date, and `env.hourCycle` whenever you format a time. The user’s 24-hour setting is separate from the locale on Android, so `Intl` only honors it when you pass `hourCycle`. Use `env.measurementSystem` to choose between kilometers and miles, or Celsius and Fahrenheit, and `env.firstDayOfWeek` when you draw a week. ### Intl support on Android [Section titled “Intl support on Android”](#intl-support-on-android) Android widgets have `Intl.Collator`, `Intl.NumberFormat`, `Intl.DateTimeFormat` and the `toLocale*` methods. They do not have `Intl.PluralRules`, `Intl.RelativeTimeFormat`, `Intl.ListFormat`, `Intl.DisplayNames` or `Intl.Locale`. Calling one of those throws, and i18n libraries that rely on plural rules (i18next 21 and newer, FormatJS) fail without them. `Intl.Segmenter` is missing too, and the polyfills below do not add it. To use them, add the [FormatJS](https://formatjs.github.io/docs/polyfills) polyfills to Android widget bundles. Install the packages in the app: ```sh npm install @formatjs/intl-getcanonicallocales @formatjs/intl-locale @formatjs/intl-pluralrules \ @formatjs/intl-listformat @formatjs/intl-displaynames @formatjs/intl-relativetimeformat ``` Then list the languages your widgets render in: metro.config.js ```js const { getDefaultConfig } = require('expo/metro-config') const { withVoltra } = require('@use-voltra/metro') module.exports = withVoltra(getDefaultConfig(__dirname), { androidIntlPolyfills: { locales: ['en', 'pl', 'de'] }, }) ``` Locale data is loaded per language, so `pt-BR` and `pt-PT` both load `pt`. Each language adds to the Android bundle size, so list only the ones you translate into. iOS bundles are not changed. If a package is missing, Metro fails at startup with a message naming the packages to install. ## Let the app choose the language [Section titled “Let the app choose the language”](#let-the-app-choose-the-language) On Android 13 and newer, a per-app language the user picks in Settings already reaches widgets as `env.locale`. On Android 12 and older, a language your app sets with AppCompat does not reach widgets. In that case, or when your app has its own language picker, pass the language to widgets: ```ts import { setDynamicWidgetLocale } from '@use-voltra/android-client' await setDynamicWidgetLocale('pl') // every render now sees env.appLocale === 'pl' await setDynamicWidgetLocale(null) // back to the system languages ``` Every placed Dynamic Widget renders again as soon as the value is stored, and the value survives app restarts. `resolveLocale` prefers `appLocale` over every other field. The override changes the translation only. `locale`, `layoutDirection`, `hourCycle` and the other formatting fields stay as they were, and Android keeps laying out the widget in the direction of `locale`. If you translate into a right-to-left language while `locale` is left-to-right, position hand-placed content by `env.layoutDirection`, not by the language you chose. ## Translate the picker and configuration copy [Section titled “Translate the picker and configuration copy”](#translate-the-picker-and-configuration-copy) The widget picker name and description accept locale maps; see [Localizing `displayName` and `description`](/android/api/plugin-configuration#localizing-displayname-and-description). `appIntent.parameters[].title` and `options[].title` accept locale maps too. Android has no system screen that shows them, so Voltra stores them as Android string resources for a configuration screen you build in native code, where you read them as `R.string.`: | Copy | Resource name | | --------------------- | ------------------------------------------------ | | a parameter’s `title` | `voltra_widget__param__title` | | an option’s `title` | `voltra_widget__param__option_` | ``, `` and `` are lower-cased, and anything other than letters, digits and underscores becomes `_`. Rebuild the native app after changing them. Voltra has no JavaScript API that reads them, so a configuration screen written in React Native needs its own copy of these translations. # Managing Android Ongoing Notifications > Start, update, and stop Android ongoing notifications from your app, including the channel, permissions, action buttons, and chip. Voltra supports Android ongoing notifications for local, app-driven status updates such as deliveries, rides, workouts, or timers. Use this API when you want to: * start a persistent notification from your app * update its content over time * stop it when the task ends * add action buttons that open deep links in your app Voltra also supports remote updates if your app receives push notifications in the background and forwards the payload to the ongoing notification APIs. See [Remote Ongoing Notifications](/android/development/remote-ongoing-notifications) for the server-side rendering API and full push integration guide. ## Before you start [Section titled “Before you start”](#before-you-start) ### 1. Enable notification manifest support [Section titled “1. Enable notification manifest support”](#1-enable-notification-manifest-support) Add `android.enableNotifications` to the Voltra Expo plugin config: ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "enableNotifications": true } ] ] } } ``` This adds the Android manifest entries required by Voltra’s notification features. See [Plugin Configuration](/android/api/plugin-configuration#enablenotifications-optional) for details. ### 2. Create a notification channel [Section titled “2. Create a notification channel”](#2-create-a-notification-channel) `channelId` is required when starting an ongoing notification, and the channel must already exist. If you use `expo-notifications`, you can create a channel like this: ```tsx import * as Notifications from 'expo-notifications' await Notifications.setNotificationChannelAsync('delivery_updates', { name: 'Delivery updates', importance: Notifications.AndroidImportance.DEFAULT, }) ``` ### 3. Request notification permission on Android 13+ [Section titled “3. Request notification permission on Android 13+”](#3-request-notification-permission-on-android-13) On Android 13 and above, posting notifications requires runtime permission. ```tsx import { hasAndroidNotificationPermission, requestAndroidNotificationPermission, } from '@use-voltra/android-client' const granted = (await hasAndroidNotificationPermission()) || (await requestAndroidNotificationPermission()) if (!granted) { // Show your own UI explaining why notifications are needed. } ``` ### 4. Check the compile SDK [Section titled “4. Check the compile SDK”](#4-check-the-compile-sdk) Voltra needs your app to compile against Android 16 (SDK 36) or later. To show [metric notifications](#metric-notification) in the full Android 17 layout, compile against SDK 37 through [expo-build-properties](https://docs.expo.dev/versions/latest/sdk/build-properties/): ```json { "expo": { "plugins": [ [ "expo-build-properties", { "android": { "compileSdkVersion": 37 } } ] ] } } ``` With SDK 36, everything else works the same, and metric notifications use the text-line fallback on every Android version. ## Starting a notification [Section titled “Starting a notification”](#starting-a-notification) Voltra provides five built-in layouts: * `AndroidOngoingNotification.Progress` — a task with a measured amount of progress * `AndroidOngoingNotification.BigText` — a paragraph of text * `AndroidOngoingNotification.BigPicture` — one image, such as a delivery photo or a map snapshot * `AndroidOngoingNotification.Inbox` — up to six short lines * `AndroidOngoingNotification.Metric` — up to three readings, such as distance, pace, and time remaining ### Progress notification [Section titled “Progress notification”](#progress-notification) ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { startAndroidOngoingNotification, } from '@use-voltra/android-client' const result = await startAndroidOngoingNotification( , { notificationId: 'order-123', channelId: 'delivery_updates', deepLinkUrl: 'myapp://orders/123', } ) if (result.ok) { console.log('Started:', result.notificationId) } ``` ### Big text notification [Section titled “Big text notification”](#big-text-notification) ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { startAndroidOngoingNotification, } from '@use-voltra/android-client' await startAndroidOngoingNotification( , { notificationId: 'match-42', channelId: 'sports_updates', } ) ``` ### Picture notification [Section titled “Picture notification”](#picture-notification) Use a picture when the image carries the status: the parcel left at the door, a snapshot of the route, the section of a climb you are on. ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { startAndroidOngoingNotification, } from '@use-voltra/android-client' await startAndroidOngoingNotification( , { notificationId: 'order-123', channelId: 'delivery_updates', } ) ``` `picture` is required and takes the same sources as every other notification image: an `assetName` you bundled or preloaded, or inline `base64`. `largeIcon` is the thumbnail you see while the notification is collapsed. The remaining picture props are optional, and the two that need a newer Android version are ignored on older devices rather than failing the update: | Prop | Effect | Needs | | --------------------------- | ------------------------------------------------------------------------------------------ | ------------------- | | `showPictureWhenCollapsed` | Fills the collapsed notification with the picture instead of showing it only when expanded | Android 12 or later | | `pictureContentDescription` | Screen reader label for the picture | Android 12 or later | | `bigLargeIcon` | Thumbnail shown while expanded, replacing `largeIcon` | - | | `hideLargeIconWhenExpanded` | Shows the `largeIcon` thumbnail only while collapsed | - | | `summaryText` | Short trailing line, such as an order number | - | **How large should the image be?** Android draws an expanded picture at 416dp by 284dp at most. Voltra hands over at most 1024 px on the long edge for a picture and 256 px for an icon, so a full-resolution camera photo buys you no extra detail and costs your app memory and decode time. A bundled drawable is handed to the system as a resource on Android 12 and later, which resizes it; on Android 11 and older Voltra draws it out to those same limits itself, so a small vector fills the picture slot on every version. **A picture notification cannot become a Live Update.** Android 16 promotes ongoing notifications with the standard, big text, call, and progress styles; `requestPromotedOngoing` is accepted for this layout and has no effect on it. If you need promotion and artwork, use `largeIcon` on a `Progress` notification. ### Lines notification [Section titled “Lines notification”](#lines-notification) Use lines when the status is a short list: the stops left on a route, the files still uploading, the steps of an order. ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { startAndroidOngoingNotification, } from '@use-voltra/android-client' await startAndroidOngoingNotification( , { notificationId: 'route-7', channelId: 'delivery_updates', } ) ``` `lines` is required and holds one to six non-empty strings. Android shows six lines at most, so the renderer rejects a seventh instead of letting it disappear from the notification. `text` is the collapsed line. If you leave it out, it takes the value of the first line. A line holds text only. There is no per-line icon, check mark, or color, so a checklist reads as a list of sentences. If you need the lines to flow as one paragraph instead, use `BigText` with newlines. ### Metric notification [Section titled “Metric notification”](#metric-notification) Show up to three readings — distance, pace, time remaining — instead of a progress bar or a text body: ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { startAndroidOngoingNotification, } from '@use-voltra/android-client' await startAndroidOngoingNotification( , { notificationId: 'run-7', channelId: 'activity_updates', } ) ``` * Pass 1 to 3 metrics, and keep each `label` between 1 and 10 characters. * A plain number is a reading and a plain string is text. `unit` next to a number is shorthand for the unit of that reading, so `{ label: 'Dist', value: 5.2, unit: 'km' }` is the same as passing the value as `{ type: 'float', value: 5.2, unit: 'km' }`. * `criticalMetric` is the index of the most important reading. Android doesn’t highlight it in the notification; it can show that reading in the [status bar chip](#showing-a-chip-in-the-status-bar) of a promoted notification. It defaults to the first reading. `semanticStyle` tints every metric: `'info'`, `'safe'`, `'caution'`, `'danger'`, or the default `'unspecified'`. * Values that change on their own: `{ type: 'timer', endsAt }` counts down to a moment and `{ type: 'stopwatch', startedAt }` counts up from it — each accepts a `Date` or an epoch timestamp, and an optional `format: 'chronometer'`. Frozen durations are `{ type: 'pausedTimer', remainingMillis }` and `{ type: 'pausedStopwatch', elapsedMillis }`. `{ type: 'time', value: '18:40' }` shows a clock time, and `{ type: 'float', value: 5.2, fractionDigits: 1 }` (with optional `min`/`max`) controls how a reading is formatted. The full metric layout needs Android 17 and later, and an app that [compiles against SDK 37](#4-check-the-compile-sdk). Otherwise the notification posts normally and the readings appear as a text line (`Dist 5.2km, Pace 5:30, ETA 9:52`), and the result carries `styleFallback: 'standard'` so you can tell. Your server can send the same metric payload to every device without knowing their versions. Time-driven values are rendered when the notification is posted, so an `updateAndroidOngoingNotification` call every minute keeps the text line fresh on those devices. Unlike the other layouts, a metric notification can be promoted to a Live Update without a `title`. ## Presentation options [Section titled “Presentation options”](#presentation-options) Everything that says how the system should treat the notification goes in the options, next to `channelId`. Everything that says what the notification means right now goes in the content, as props on the layout component, such as `AndroidOngoingNotification.Progress`. ```tsx await startAndroidOngoingNotification( , { notificationId: 'ride-44', channelId: 'ride_updates', visibility: 'private', color: '#1E88E5', category: 'navigation', timeoutMs: 30 * 60 * 1000, group: 'rides', sortKey: '2026-09-22T12:00', } ) ``` | Option | Values | Default | Applies on | After an update that omits it | | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------ | ----------------------------- | | `visibility` | `'public'`, `'private'`, `'secret'` | system default, `'private'` | all versions | kept | | `color` | any static color string: `'#1E88E5'`, `'rgb(30, 136, 229)'`, `'crimson'` | none | all versions | kept | | `category` | `'progress'`, `'navigation'`, `'transport'`, `'service'`, `'status'`, `'workout'`, `'stopwatch'`, `'location_sharing'` | from the content: a progress notification reports `'progress'`, a big text notification reports none | all versions | kept | | `timeoutMs` | milliseconds as a whole number | none, the notification stays until you stop it | Android 8.0+ | kept and the timer restarts | | `localOnly` | `true` to keep it off Wear and Android Auto | `false` | all versions | kept | | `group`, `sortKey` | group key, and the order inside it | none | all versions | kept | | `allowSystemGeneratedContextualActions` | `false` to stop the system adding its own actions, such as a directions chip | platform default, `true` | Android 10+ | kept | Notes on individual options: * `visibility` decides what the lock screen shows. `'secret'` hides the notification entirely there. Use `'private'` together with `publicVersion` to show a short copy of your own. * `color` is an accent: the system tints the notification with it, and shows it as background only for styles that support that. A color the device cannot resolve, such as a theme token, rejects the call rather than posting without a color. * `category` overrides what Voltra derives from your content, and does not change the channel. * `timeoutMs` is applied on every post, so each update restarts the countdown and a notification that stops being updated eventually disappears on its own. Once the system removes it, `getAndroidOngoingNotificationStatus()` reports it as no longer active, and starting that `notificationId` again needs `stopAndroidOngoingNotification()` first, the same as after a swipe. On Android 7.x and older the value is kept but not applied. * `group` puts the notification in the bundle the system builds from notifications sharing the key. Voltra does not post a group summary of its own. ### Lock-screen copy [Section titled “Lock-screen copy”](#lock-screen-copy) `publicVersion` is a prop on the content, not an option: it is text, so an update replaces it, and an update that leaves it out posts without one. ```tsx ``` The copy is what the lock screen shows when `visibility` hides the real content. It carries the title and text you give it and nothing else: no progress, no action buttons. ### Timestamps [Section titled “Timestamps”](#timestamps) `showWhen` (default `true`, and `false` when the payload carries no timestamp) hides the time the notification shows while keeping the timestamp for sorting and timeouts. Set it to `false` for an absolute deadline, so the notification stops claiming it is “5 minutes ago”. To count down to `when` instead, use `chronometer="countDown"` (see [Showing a chip in the status bar](#showing-a-chip-in-the-status-bar)). ```tsx ``` ### Changing a presentation option [Section titled “Changing a presentation option”](#changing-a-presentation-option) An update keeps every presentation option you do not mention. To change one, send it; to go back to the platform default, send `null`: ```tsx await updateAndroidOngoingNotification('ride-44', content, { channelId: 'ride_updates', color: '#000000', // replace timeoutMs: null, // stop timing this one out // group and sortKey left out: they keep their stored values }) ``` The pre-existing options (`smallIcon`, `deepLinkUrl`, `requestPromotedOngoing`, `fallbackBehavior`) behave as before: leaving one out reuses the stored value, and there is no way to clear them. `upsertAndroidOngoingNotification()` takes the same options, and the `null` clears mean the same thing there when the call ends up updating. When it ends up starting, nothing is stored to clear and the calls behave like a start. ### Letting one update make a sound [Section titled “Letting one update make a sound”](#letting-one-update-make-a-sound) An ongoing notification alerts when it is first posted and is silent afterwards. `alert` is an update option that lets one update alert again: ```tsx await updateAndroidOngoingNotification('ride-44', content, { channelId: 'ride_updates', alert: true, }) ``` It applies to that post only and is never stored, so the next update is quiet again. Whether it audibly alerts is still decided by the channel you created: a channel on low importance stays silent however you set `alert`. `upsertAndroidOngoingNotification()` takes it too: it alerts when that call ends up updating, and a first post always alerts anyway. ## Updating a notification [Section titled “Updating a notification”](#updating-a-notification) Use the same `notificationId` to update an existing notification. ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { updateAndroidOngoingNotification, } from '@use-voltra/android-client' await updateAndroidOngoingNotification( 'order-123', ) ``` `updateAndroidOngoingNotification()` returns a result object. If the notification no longer exists, it returns `reason: 'not_found'` or `reason: 'dismissed'`. ## Starting or updating with one call [Section titled “Starting or updating with one call”](#starting-or-updating-with-one-call) If your app may re-enter the same flow multiple times, `upsertAndroidOngoingNotification()` can be easier than separate start/update logic. ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { upsertAndroidOngoingNotification, } from '@use-voltra/android-client' const result = await upsertAndroidOngoingNotification( , { notificationId: 'workout-1', channelId: 'fitness_updates', } ) if (result.ok) { console.log(result.action) // 'started' or 'updated' } ``` This API is especially useful for remote updates, where the same incoming push may need to create the notification the first time and update it later. It takes the same options as the other two calls: a presentation option sent as `null` clears the stored value and `alert` makes the update branch alert, both only when the call ends up updating. ## Stopping a notification [Section titled “Stopping a notification”](#stopping-a-notification) ```tsx import { stopAndroidOngoingNotification } from '@use-voltra/android-client' await stopAndroidOngoingNotification('order-123') ``` To dismiss every active Voltra ongoing notification at once: ```tsx import { endAllAndroidOngoingNotifications } from '@use-voltra/android-client' await endAllAndroidOngoingNotifications() ``` ## Hook API [Section titled “Hook API”](#hook-api) For React screens and flows, use `useAndroidOngoingNotification()`. ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' import { useAndroidOngoingNotification } from '@use-voltra/android-client' function DeliveryNotification({ orderId, etaMinutes }) { const { start, update, end, isActive } = useAndroidOngoingNotification( , { notificationId: `order-${orderId}`, channelId: 'delivery_updates', deepLinkUrl: `myapp://orders/${orderId}`, autoStart: true, autoUpdate: true, } ) return null } ``` The hook returns: * `start()` * `update()` * `end()` * `isActive` Use `autoStart` to create the notification when the component mounts, and `autoUpdate` to refresh it when the JSX content changes. ## Action buttons [Section titled “Action buttons”](#action-buttons) You can add action buttons as children of any layout. ```tsx import { AndroidOngoingNotification } from '@use-voltra/android' ``` Action buttons currently: * open the provided deep link * can be used with `Progress`, `BigText`, `BigPicture`, `Inbox`, and `Metric` * support an optional `icon` ```tsx ``` Android may not show action icons in the standard notification UI, so treat them as optional enhancement rather than a guaranteed visual element. ## Main tap behavior [Section titled “Main tap behavior”](#main-tap-behavior) Use `deepLinkUrl` in the start or update options to control what happens when the user taps the main notification body: ```tsx await startAndroidOngoingNotification(content, { notificationId: 'order-123', channelId: 'delivery_updates', deepLinkUrl: 'myapp://orders/123', }) ``` This is separate from action button deep links. ## Showing a chip in the status bar [Section titled “Showing a chip in the status bar”](#showing-a-chip-in-the-status-bar) On Android 16 and above, a promoted ongoing notification shows a chip in the status bar. You fill it with either a short text or a clock: ```tsx ``` * `shortCriticalText` shows a short text in the chip. Keep it to about 7 characters; the chip is at most 96dp wide and longer text is cut. * `chronometer: true` shows elapsed time since `when`, counting up. `'countUp'` means the same as `true`. * `chronometer: 'countDown'` shows the time remaining until `when`, counting down — the right choice for an ETA, a timer, or a parking meter. It requires `when`; rendering throws without it. When you set several of these, the chip picks one in this order: 1. `shortCriticalText` (an empty string means no chip text at all) 2. for a metric notification on Android 17 and later, the value of the `criticalMetric` 3. time derived from `when` — the chronometer when `chronometer` is set, otherwise the remaining time ## Status and capability helpers [Section titled “Status and capability helpers”](#status-and-capability-helpers) Use these helpers to adapt your UI to the device state: ```tsx import { canPostPromotedAndroidNotifications, getAndroidOngoingNotificationCapabilities, getAndroidOngoingNotificationStatus, openAndroidNotificationSettings, openAndroidPromotedNotificationSettings, } from '@use-voltra/android-client' const status = getAndroidOngoingNotificationStatus('order-123') const capabilities = getAndroidOngoingNotificationCapabilities() const canPostPromoted = canPostPromotedAndroidNotifications() if (!capabilities.notificationsEnabled) { await openAndroidNotificationSettings() } ``` Useful values include: * `status.isActive` * `status.isDismissed` * `status.isPromoted` and `status.hasPromotableCharacteristics` — set on Android 16 and above, `undefined` below it * `capabilities.notificationsEnabled` * `capabilities.supportsPromotedNotifications` * `capabilities.canPostPromotedNotifications` * `capabilities.canRequestPromotedOngoing` `openAndroidNotificationSettings()` opens your app’s channel list. When the user has turned Live Updates off for your app (`canPostPromotedNotifications === false`), use `openAndroidPromotedNotificationSettings()` to open the page where they turn them back on. It resolves `true` when the Live Updates page opened and `false` when the regular notification settings opened instead, because the device has no such page. ## When posting fails [Section titled “When posting fails”](#when-posting-fails) Start, update, and upsert reject with a code instead of posting something broken: | Code | What happened | What to do | | --------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------- | | `VOLTRA_NOTIFICATION_CHANNEL_REQUIRED` | No `channelId` was given | Pass `channelId` in the start options | | `VOLTRA_NOTIFICATION_CHANNEL_NOT_FOUND` | The channel was never created — Android drops such notifications silently | Create the channel before posting | | `VOLTRA_NOTIFICATION_INVALID_PAYLOAD` | The payload is malformed or breaks a rule (e.g. a remote payload with `chronometerCountDown` but no `when`) | Fix the payload | | `VOLTRA_NOTIFICATION_INVALID_OPTIONS` | An option cannot be applied on this device (e.g. a `color` that is a theme token rather than a static color) | Pass a static color such as `'#1E88E5'` | | `VOLTRA_NOTIFICATION_NOT_PROMOTABLE` | Promotion was requested with `fallbackBehavior: 'error'` and the notification is not eligible | Read the reasons in the message (see below) | | `VOLTRA_NOTIFICATION_INTERNAL_ERROR` | An unexpected device failure | Retry; if it persists, file an issue with the message | A dismissed notification is different: updates return `ok: false, reason: 'dismissed'` and nothing is re-posted. If your flow legitimately restarts after a dismissal, start a new notification instead of updating. ## Promoted ongoing notifications [Section titled “Promoted ongoing notifications”](#promoted-ongoing-notifications) On Android 16 and above, eligible ongoing notifications can be promoted to Live Updates: they expand into the status bar and show up on the lock screen and home screen. Pass `requestPromotedOngoing: true` to ask for it: ```tsx const result = await startAndroidOngoingNotification(content, { notificationId: 'ride-44', channelId: 'ride_updates', requestPromotedOngoing: true, }) ``` You don’t need the user to have turned Live Updates on first. Voltra records the request on every post, so when the user enables Live Updates in Settings, the next update is promoted without any change in your app. ### Reading why a notification is not promoted [Section titled “Reading why a notification is not promoted”](#reading-why-a-notification-is-not-promoted) When you request promotion, a successful result carries a `promotion` object: ```tsx if (result.ok && result.promotion) { console.log(result.promotion.eligible, result.promotion.reasons) } ``` * `promotion.requested` — always `true` when the object is present * `promotion.eligible` — `true` when the notification can be promoted * `promotion.reasons` — what stands in the way, as a list * `promotion.hasPromotableCharacteristics` — the platform’s own verdict on the built notification; only set on Android 16 and above | Reason | Meaning | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `unsupported_api_level` | The device runs below Android 16 | | `permission_not_declared` | `enableNotifications` is not on, so `POST_PROMOTED_NOTIFICATIONS` is missing from the manifest. Android 16 QPR2 and later only; Android 16.0 has no such permission | | `notifications_disabled` | Notifications are turned off for your app | | `promotion_disabled_by_user` | The user turned Live Updates off for your app | | `channel_importance_min` | The channel’s importance is `MIN`; use at least `LOW` | | `missing_title` | The notification has no `title`; promotion requires one | | `not_promotable` | The platform rejected the built notification for another reason | With the default `fallbackBehavior: 'standard'`, a notification that cannot be promoted is still posted as a normal ongoing notification and you read the reasons from the result. With `fallbackBehavior: 'error'`, the call rejects with `VOLTRA_NOTIFICATION_NOT_PROMOTABLE`, the message lists the reasons, and nothing is posted. ### Checking before you post [Section titled “Checking before you post”](#checking-before-you-post) `checkAndroidOngoingNotificationPromotion()` answers the same questions for a payload without posting it or recording anything: ```tsx import { checkAndroidOngoingNotificationPromotion } from '@use-voltra/android-client' const check = await checkAndroidOngoingNotificationPromotion(content, { channelId: 'ride_updates', }) if (!check.eligible) { console.warn('Would not promote:', check.reasons) } ``` Only `Progress` and `BigText` can be promoted. Android decides which layouts qualify, and a `BigPicture` or `Inbox` notification stays a standard ongoing notification even when you ask for promotion: the call succeeds, `requestPromotedOngoing` is remembered, and nothing is promoted. Check `status.hasPromotableCharacteristics` if you want to show the user why. ## What Voltra does not cover [Section titled “What Voltra does not cover”](#what-voltra-does-not-cover) Some Android notification templates look like ongoing status updates and are not one. Voltra does not build them: * **Conversations (`MessagingStyle`)** — needs `Person` objects, a conversation title, a direct reply field, and a long-lived shortcut on Android 11 and later. Use `expo-notifications` or Notifee. * **Playback controls (`MediaStyle`)** — needs a `MediaSession` token, which a media library owns and builds the notification from. Use Media3, `expo-notifications`, or Notifee. * **Bubbles** — need a pushed long-lived shortcut and a conversation, and Voltra does not own your host activity or your shortcuts. Use `expo-notifications` or Notifee. * **Full-screen intents** — an interruption, not a status. Android 14 grants `USE_FULL_SCREEN_INTENT` by default only to calling and alarm apps, and Google Play revokes it for others. Use `expo-notifications` or Notifee when you genuinely need one. A common combination is a Voltra ongoing notification for the status plus one of those templates posted through another library. ## Current limitations [Section titled “Current limitations”](#current-limitations) * Remote updates require your own push delivery and background task integration. See [Remote Ongoing Notifications](/android/development/remote-ongoing-notifications). * A push carrying a `bigPicture` or `inbox` payload reaches only app builds that know those payload kinds. See [Compatibility](/android/development/remote-ongoing-notifications#compatibility). * Your app must create the Android notification channel before starting a notification. * Notification permission still needs to be requested by your app on Android 13+. * Action buttons open deep links. They are not a JavaScript event system. * Some Android notification fields stay out of the API on purpose: * Badge count and badge icon. The launcher dot belongs to the channel your app creates, and a count makes no sense for a single ongoing item. * Group summary. Voltra posts no summary, and requesting one disqualifies the notification from promoted presentation. * A color background on every notification (`colorized`). It does nothing for these styles outside a foreground service, which Voltra does not run, and it also disqualifies promoted presentation. * Tapping to auto-dismiss. The ongoing lifecycle belongs to `stopAndroidOngoingNotification()`, and a tap-dismiss would leave the notification recorded as active while it is already gone. * Sound, vibration, lights and their defaults, and importance. All of them are channel settings since Android 8.0. * Priority below Android 8.0. Deprecated, and a second API level to document for the same result. * A settings line under the notification, which needs a notification-preferences intent filter in your manifest, and the deprecated extra content-info line. * A ticker, which older accessibility services read while TalkBack reads the title and text anyway. * Whether a grouped notification alerts with its group. That only means something together with a summary Voltra does not post. # Native modifiers > Apply Jetpack Glance modifiers that style does not cover, such as semantics and appWidgetBackground, with the modifiers prop. Native modifiers apply Jetpack Glance modifiers that `style` does not cover, such as `semantics`, `appWidgetBackground` and day/night backgrounds, to any Voltra Android component. Use them in Dynamic Widgets Native modifiers are meant for [Dynamic Widgets](/android/development/dynamic-widgets). [Payload widgets](/android/development/server-driven-widgets) accept them too, but every modifier is stored and sent with every update, which makes the payload larger. ## Add a modifier [Section titled “Add a modifier”](#add-a-modifier) Pass a list of modifiers from `VoltraAndroid.modifiers` to the `modifiers` prop: ```tsx import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android' const { appWidgetBackground, background, semantics, visibility } = VoltraAndroid.modifiers export default function PortfolioWidget({ balance, stale }: { balance: string; stale: boolean }) { return ( {balance} Updating… ) } ``` `VoltraAndroid` components only accept modifiers from `VoltraAndroid.modifiers`. Passing a modifier from `Voltra.modifiers`, or a plain object, is a TypeScript error. ## How modifiers combine with `style` [Section titled “How modifiers combine with style”](#how-modifiers-combine-with-style) Glance applies modifiers after `style`, and it does not care about their order: * Where a modifier and a `style` property set the same thing, such as a width or a background, the modifier wins. There are three exceptions: * `style.flex` on a child of a `Row` or `Column` replaces the child’s `width`, `height`, `size`, `fillMax…` and `wrapContent…` modifiers along the row or column. * A `Scaffold` always fills the widget and draws its own background and rounded corners, so size modifiers, `background` and `cornerRadius` on the `Scaffold` itself have no effect. Use its `backgroundColor` prop instead. * `FilledButton`, `OutlineButton`, `CircleIconButton` and `SquareIconButton` draw their own background and rounded corners, so `background` and `cornerRadius` on them have no effect. Use their color props instead. * `Chart`, `ArcProgressIndicator` and `Text` with `renderAsBitmap` take their size from the size modifiers. `wrapContentWidth`, `wrapContentHeight` and `wrapContentSize` on them keep their default size. * Padding adds up. `style={{ padding: 8 }}` with `modifiers={[padding(8)]}` gives 16 dp. * Using the same modifier twice keeps the last one, except for `padding` and `absolutePadding`, which add up. ## Available modifiers [Section titled “Available modifiers”](#available-modifiers) | Modifier | What it does | | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `padding(dp \| { all?, horizontal?, vertical?, start?, top?, end?, bottom? })` | Adds padding that follows the layout direction. | | `absolutePadding(dp \| { all?, horizontal?, vertical?, left?, top?, right?, bottom? })` | Adds padding that ignores the layout direction. | | `width(dp)`, `height(dp)`, `size(dp \| { width, height })` | Sets a fixed size. | | `fillMaxWidth()`, `fillMaxHeight()`, `fillMaxSize()` | Fills the available space. | | `wrapContentWidth()`, `wrapContentHeight()`, `wrapContentSize()` | Sizes to the content. | | `background(color \| { day, night })` | Fills the background with a color, an `AndroidDynamicColors` token, or separate light and dark colors. | | `cornerRadius(dp)` | Rounds the corners. Android 12+. | | `visibility('visible' \| 'invisible' \| 'gone')` | Shows the component, hides it but keeps its space, or removes it from layout. | | `semantics({ contentDescription?, testTag? })` | Sets the text read by accessibility services. `testTag` is only visible to Glance’s own test APIs, not to UI tests of the widget on a device. At least one of the two is required. | | `appWidgetBackground()` | Marks the widget background so the launcher can animate it when the widget opens your app. Use it once, on the outermost component. If several components set it, only one keeps it. Inside a widget with a `Scaffold`, it is skipped because the `Scaffold` marks its own background. Android 12+. | For light and dark colors, `background({ day, night })` takes two static color strings; `AndroidDynamicColors` tokens are a type error there. To follow the device’s Material You theme instead, pass an `AndroidDynamicColors` token. See [Dynamic Colors](/android/development/dynamic-colors). Native modifiers do not handle taps. To open your app from a component, use its `deepLinkUrl` prop. ## Troubleshooting [Section titled “Troubleshooting”](#troubleshooting) **Corners are not rounded.** `cornerRadius` only works on Android 12 (API 31) and later. Older versions render square corners. **A modifier has no effect.** An unknown modifier or an invalid value, such as a color string that does not parse or `day` and `night` given as `AndroidDynamicColors` tokens, is skipped. Run `adb logcat -s VoltraModifiers` to see which one and why. **The launcher does not animate the widget when it opens the app.** `appWidgetBackground` only works on Android 12 (API 31) and later. Older versions open the app without the animation. **The padding is larger than expected.** Glance adds `padding` modifiers to `style.padding`. Remove one of them. # Querying Active Widgets > Find every Voltra widget instance placed on the Android Home Screen, with its appWidgetId, widget type, and size, using getActiveWidgets. On Android, you can detect every active instance of your widgets currently placed on the Home Screen. This is particularly useful for Android since each widget instance can have different dimensions and a unique `appWidgetId`. ## getActiveWidgets API [Section titled “getActiveWidgets API”](#getactivewidgets-api) The `getActiveWidgets` function returns a promise that resolves to an array of all active widget instances for your app. ```typescript import { getActiveWidgets } from '@use-voltra/android-client' async function checkAndroidWidgets() { const activeWidgets = await getActiveWidgets() console.log(`Found ${activeWidgets.length} active widget instances`) activeWidgets.forEach(widget => { console.log(`- Widget: ${widget.widgetType}`) console.log(` Placement: ${widget.appWidgetId}`) console.log(` Size: ${widget.width}x${widget.height}dp`) }) } ``` ### WidgetInfo Object [Section titled “WidgetInfo Object”](#widgetinfo-object) Each object in the returned array contains: | Property | Type | Description | | ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `widgetType` | `string` | The Voltra widget ID as defined in your Expo config plugin (e.g., `"weather"`). | | `appWidgetId` | `number` | The Android identifier of this placement. Pass it to the [per-instance configuration APIs](/android/development/dynamic-widgets#configure-each-placed-widget-separately) to give one placement its own values. | | `providerClassName` | `string` | The full class name of the widget provider (e.g., `".widget.VoltraWidget_weatherReceiver"`). | | `label` | `string` | The human-readable label shown in the Android widget picker. | | `width` | `number` | The current width of the widget instance in dp. | | `height` | `number` | The current height of the widget instance in dp. | | `name` | `string` | **Deprecated.** Renamed to `widgetType`, which says what it holds. Same value. | | `widgetId` | `number` | **Deprecated.** Renamed to `appWidgetId`. It is the Android placement identifier, not the Voltra widget ID that `widgetId` names everywhere else in this package. Same value. | The same widget placed twice appears twice, with one entry per placement and a different `appWidgetId` on each. # Remote Ongoing Notifications (Android) > Update Android ongoing notifications from push messages handled in a background task, with server-side rendering support. Voltra can apply remote updates to an ongoing notification when your app receives a push notification and handles it in a background task. This builds on the local lifecycle API — see [Managing Ongoing Notifications](/android/development/managing-ongoing-notifications) first for creating the notification channel, requesting permission, and the start/update/stop APIs. ## Server-side rendering support [Section titled “Server-side rendering support”](#server-side-rendering-support) Voltra provides a server-side API for converting JSX into the semantic payload used by Android ongoing notifications. Use these APIs only in server-side or backend code. Do not import them from your React Native app runtime. Use `@use-voltra/android-server`. The main renderer APIs are: * `renderAndroidOngoingNotificationPayloadToJson()` returns an object * `renderAndroidOngoingNotificationPayload()` returns a JSON string This API only renders the payload. Your server still needs to send that payload through your push provider, and your app still needs a background task that calls `upsertAndroidOngoingNotification()` or `stopAndroidOngoingNotification()` when the push arrives. ## Register a background notification task [Section titled “Register a background notification task”](#register-a-background-notification-task) You should use `expo-notifications` together with `expo-task-manager` to process real push notifications and update ongoing notifications in the background. Register a background task early in app startup, so incoming pushes can update or stop an ongoing notification even when the app is backgrounded: ```tsx import * as Notifications from 'expo-notifications' import * as TaskManager from 'expo-task-manager' const TASK_NAME = 'voltra-ongoing-notification-task' TaskManager.defineTask(TASK_NAME, async ({ data, error }) => { if (error) { return } // Read your push payload and call Voltra APIs here. }) await Notifications.registerTaskAsync(TASK_NAME) ``` ## The remote update flow [Section titled “The remote update flow”](#the-remote-update-flow) The end-to-end flow is: 1. Your server renders Voltra JSX into an Android ongoing-notification payload. 2. Your server sends a high-priority push notification. 3. The push `data` contains a `voltraOngoingNotification` object. 4. Your background task parses that object. 5. The task calls `upsertAndroidOngoingNotification()` or `stopAndroidOngoingNotification()`. ### 1. Render the payload on your server [Section titled “1. Render the payload on your server”](#1-render-the-payload-on-your-server) Use `renderAndroidOngoingNotificationPayloadToJson()` when preparing a payload on your server or in app tooling: ```tsx import { AndroidOngoingNotification, renderAndroidOngoingNotificationPayloadToJson, } from '@use-voltra/android-server' const payload = renderAndroidOngoingNotificationPayloadToJson( ) ``` Then send that payload inside a push message. A picture works the same way: ```tsx const payload = renderAndroidOngoingNotificationPayloadToJson( ) ``` ```json { "v": 1, "kind": "bigPicture", "title": "Parcel delivered", "text": "Left at the front door", "picture": { "assetName": "delivery_photo_123" }, "summaryText": "Order 123" } ``` An `inbox` payload carries its lines in the same shape: ```tsx const payload = renderAndroidOngoingNotificationPayloadToJson( ) ``` ```json { "v": 1, "kind": "inbox", "title": "3 stops remaining", "text": "12 Oak Street", "lines": ["12 Oak Street", "4 Elm Road", "Depot"], "summaryText": "Route 7" } ``` If your push provider expects strings for nested payload data, use `renderAndroidOngoingNotificationPayload()` instead and send the JSON string directly. ### 2. Send the payload through your push provider [Section titled “2. Send the payload through your push provider”](#2-send-the-payload-through-your-push-provider) Your payload’s `data.voltraOngoingNotification` should contain: * `notificationId`: the stable notification identifier * `operation`: `'upsert'` or `'stop'` * `options`: start options such as `channelId`, `smallIcon`, `deepLinkUrl`, `requestPromotedOngoing`, or `fallbackBehavior`; the presentation options `visibility`, `color`, `category`, `timeoutMs`, `localOnly`, `group`, `sortKey`, and `allowSystemGeneratedContextualActions`; and `alert` * `payload`: the Voltra semantic payload for `'upsert'` Presentation options are the app’s decision, so send them only if your push builder is allowed to make it. An upsert whose `options` leaves them out changes nothing about how the running notification is presented, and a presentation option sent as `null` clears the stored value when the push updates an existing notification. `alert: true` makes an updating push alert the way a first post does; a push that starts a notification always alerts anyway. The payload itself can carry `publicVersion`, `showWhen`, and `chronometerCountDown`, like any other content field. Example Expo push request: ```json { "to": "ExponentPushToken[project-token]", "priority": "high", "data": { "voltraOngoingNotification": "{\"notificationId\":\"order-123\",\"operation\":\"upsert\",\"options\":{\"channelId\":\"delivery_updates\",\"deepLinkUrl\":\"myapp://orders/123\",\"requestPromotedOngoing\":true,\"visibility\":\"private\",\"color\":\"#1E88E5\",\"category\":\"navigation\",\"timeoutMs\":1800000,\"group\":\"deliveries\"},\"payload\":{\"v\":1,\"kind\":\"progress\",\"title\":\"Driver is approaching\",\"text\":\"2 stops away\",\"value\":80,\"max\":100,\"when\":1758540000000,\"showWhen\":false,\"publicVersion\":{\"title\":\"Delivery in progress\",\"text\":\"Unlock to see the driver\"}}}" } } ``` Voltra accepts either an object or a JSON string for `data.voltraOngoingNotification`. Stringifying it is often the safest option when sending through push providers. To stop the notification remotely, send the same `notificationId` with `operation: "stop"` and omit `payload`. **Pictures in a remote payload.** A `bigPicture` or `largeIcon` entry in a push payload should reference an image the app can already find, through `assetName` for a bundled or preloaded image. Android push providers cap the data of a message well below the size of a photo — Firebase caps a data message at 4096 bytes — so a `base64` picture does not fit. Download the image on the device with `preloadImages()` from `@use-voltra/android-client`, see [Image Preloading](/android/development/image-preloading), and send its key. ### 3. Apply the payload in your background task [Section titled “3. Apply the payload in your background task”](#3-apply-the-payload-in-your-background-task) ```tsx import * as Notifications from 'expo-notifications' import * as TaskManager from 'expo-task-manager' import { stopAndroidOngoingNotification, upsertAndroidOngoingNotification, } from '@use-voltra/android-client' const TASK_NAME = 'voltra-ongoing-notification-task' const parseMessage = (value: unknown) => { if (typeof value === 'string') { try { return JSON.parse(value) } catch { return null } } return value } TaskManager.defineTask(TASK_NAME, async ({ data, error }) => { if (error) { return } const message = parseMessage(data?.voltraOngoingNotification) if (!message || typeof message !== 'object') { return } const notificationId = typeof message.notificationId === 'string' ? message.notificationId : null if (!notificationId) { return } if (message.operation === 'stop') { await stopAndroidOngoingNotification(notificationId) return } if (!message.payload || !message.options?.channelId) { return } await upsertAndroidOngoingNotification(message.payload, { ...message.options, notificationId, }) }) await Notifications.registerTaskAsync(TASK_NAME) ``` When the options request promotion, a successful upsert result carries `result.promotion.reasons` — the machine-readable list of what would block promotion on this device — so your handler can log it. A payload that breaks a rule (`kind` unknown, malformed JSON, a countdown without `when`) rejects with a `VOLTRA_NOTIFICATION_...` code instead of posting something broken, and a channel that was never created rejects too. Wrap the call in `try`/`catch` if you want to react to those. `AndroidOngoingNotification.Metric` renders server-side too, so one metric payload fits every device: below Android 17 it posts as a standard notification whose text line joins the readings, and the upsert result then carries `styleFallback: 'standard'`. ### Channel setup for remote updates [Section titled “Channel setup for remote updates”](#channel-setup-for-remote-updates) Your background task should ensure that the target notification channel exists before calling `upsertAndroidOngoingNotification()`. Create the channel on startup, and also ensure it exists again inside the background handler. ## Compatibility [Section titled “Compatibility”](#compatibility) The client chooses its parser by the `kind` field, so your server and the installed app have to agree on the available kinds. A build that does not know `bigPicture` or `inbox` fails to parse that payload rather than falling back to a layout it does know, and the update is reported as a failure. Serve `progress` or `bigText` to older installs, which means a server that picks a layout per device needs the app version that device reports. # Server-driven widgets > Have Android widgets fetch fresh content from your server with WorkManager on a schedule, without the user opening the app. Server-driven widgets allow your Android Home Screen widgets to periodically fetch fresh content from a remote server—without the user opening the app. This is powered by WorkManager, which handles scheduling, retries, and network constraints automatically. Before you start, make sure the widget is registered in the Voltra plugin config and plan to rebuild the native app after adding or changing server-driven widget settings. Android semantic color tokens from [`AndroidDynamicColors`](/android/development/dynamic-colors) work in server-rendered widgets too, so your backend can return dynamic Material roles instead of fixed hex values. ## How it works [Section titled “How it works”](#how-it-works) 1. You configure a `serverUpdate` URL in your Android widget’s plugin config 2. WorkManager runs a periodic background task at the configured interval 3. Your server renders Voltra JSX components into a JSON payload 4. The worker parses the payload and pushes a `RemoteViews` update to the widget Your app doesn’t need to be running. WorkManager handles everything in the background. A widget that also has an `entry` works the other way round: your server returns plain JSON data and the widget renders it on the device, so the backend can be written in any language. See [Returning data instead of UI](#returning-data-instead-of-ui). ## Plugin configuration [Section titled “Plugin configuration”](#plugin-configuration) Add the `serverUpdate` option to your Android widget in `app.json` or `app.config.js`: ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "widgets": [ { "id": "dynamic_weather", "displayName": "Dynamic Weather", "description": "Weather with live server updates", "targetCellWidth": 2, "targetCellHeight": 1, "serverUpdate": { "url": "https://api.example.com/widgets/render", "intervalMinutes": 60 } } ] } ] ] } } ``` **`serverUpdate` options:** * `url`: The endpoint the widget fetches from. Voltra appends `widgetId`, `platform`, `theme`, and `locale` query parameters automatically (e.g. `?widgetId=dynamic_weather&platform=android&theme=dark&locale=en-US`). Optional — leave it out to mark the widget server-driven and supply the URL after login with [`setWidgetServerUpdate`](#changing-settings-at-runtime). * `intervalMinutes`: How often the widget fetches updates. Defaults to `60`, or `15` for a widget that has an `entry`. The minimum is 15 minutes. * `refresh`: Whether to show a native refresh button in the top-right corner of the widget. When tapped, triggers an immediate server fetch. Defaults to `false`. After updating plugin configuration, run `npx expo prebuild` if you’re using Continuous Native Generation, then rebuild the app so the generated native widget code picks up the new server update settings. Note On the Android emulator, use `10.0.2.2` instead of `localhost` to reach the host machine. Real devices need the host’s LAN IP address. ## Building the server [Section titled “Building the server”](#building-the-server) Voltra provides widget server handlers for the common runtime styles. Use `createAndroidWidgetUpdateHandler()` for Fetch-compatible runtimes, `createAndroidWidgetUpdateNodeHandler()` for `node:http`, and `createAndroidWidgetUpdateExpressHandler()` for Express-style handlers. All three share the same request parsing, platform validation, token validation, and response serialization. ```tsx import { createServer } from 'node:http' import React from 'react' import { createAndroidWidgetUpdateNodeHandler } from '@use-voltra/android-server' import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android' const handler = createAndroidWidgetUpdateNodeHandler({ render: async (req) => { // req.widgetId — the widget requesting an update // req.platform — always "android" for Android widget requests // req.theme — the system color scheme ("light" or "dark") // req.token — the auth token (if credentials were set) const weather = await fetchWeatherData() const content = ( {weather.temp}° {weather.condition} ) // Return size breakpoints for different widget sizes return [ { size: { width: 200, height: 100 }, content }, { size: { width: 200, height: 200 }, content }, { size: { width: 300, height: 200 }, content }, ] }, validateToken: async (token) => { return token === 'valid-token' }, }) createServer(handler).listen(3333) ``` The handler responds to GET requests with these query parameters: | Parameter | Description | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `widgetId` | The widget identifier (required) | | `platform` | The requesting platform. Must be `android` (required). | | `family` | Not used on Android | | `theme` | The system color scheme (`light` or `dark`) | | `locale` | The device locale as a BCP-47 tag, e.g. `en-US` | | `instance` | A stable hash of the placement’s merged configuration. Present only when the widget has configuration parameters (see [Per-instance requests](#per-instance-requests)). | | `configuration` | The placement’s merged configuration as canonical JSON. Present only when the widget has configuration parameters. | The `User-Agent` header is set to `VoltraWidget/ (Android/)`. ### Per-instance requests [Section titled “Per-instance requests”](#per-instance-requests) Each placed widget can be configured independently (see [Configure each placed widget separately](/android/development/dynamic-widgets#configure-each-placed-widget-separately)). When a widget has configuration parameters, every request carries the placement’s merged configuration — defaults, overlaid with widget-type values, overlaid with the placement’s own values — so a server can answer each placement differently: ```plaintext GET https://api.example.com/widgets/weather ?widgetId=weather&platform=android&theme=dark&locale=en-US &instance=3f9a2c1e &configuration=%7B%22city%22%3A%22London%22%2C%22units%22%3A%22metric%22%7D ``` * `configuration` is the merged configuration map, serialized canonically: keys sorted by code point, no whitespace, values as JSON strings. Decoded, it is exactly what the widget sees as `env.configuration`. * `instance` is a stable, non-cryptographic hash of that canonical string. Two placements with identical configuration send the same `instance` and share one fetch, one cached response, and one props slot — placing the same widget twice with the same values does not double your request volume. * Both parameters are absent when the widget has no configuration parameters at all, so an existing server-driven widget’s requests are unchanged by this feature. * `instance` and `configuration` are reserved query keys: a `query` you pass to `setWidgetServerUpdate` naming either is rejected. Configurations are meant for identifiers and short choices, not large payloads — percent-encoding roughly triples the size of braces and quotes in the JSON. **Fetch count.** A server-driven widget fetches once per distinct configuration among its current placements, not once per placement. If ten placements of one widget each use a different value for a free-text parameter, that is ten fetches per interval (each still floored at 15 minutes) rather than one. A server can still stretch the interval per instance with `Cache-Control: max-age`, exactly as it can today. A widget with no configuration parameters keeps behaving exactly as it did before: one request, one cached response, shared by every placement. ## Returning data instead of UI [Section titled “Returning data instead of UI”](#returning-data-instead-of-ui) Everything above assumes your server renders Voltra components and returns a UI payload, which means it has to run Node. If you give the widget an `entry`, it renders on the device instead and your server returns plain JSON — so it can be written in any language. Add both keys to the same widget: ```json { "id": "portfolio", "displayName": "Portfolio", "description": "Your holdings", "targetCellWidth": 2, "targetCellHeight": 2, "entry": "./widgets/android/portfolio.tsx", "initialStatePath": "./widgets/android/portfolio.tsx", "serverUpdate": { "url": "https://api.example.com/widgets/portfolio", "intervalMinutes": 30 } } ``` The response body becomes the widget’s props, verbatim: ```php 12480.55, 'change' => 1.8, 'holdings' => [ ['symbol' => 'AAPL', 'value' => 8200.00], ['symbol' => 'MSFT', 'value' => 4280.55], ], ]); ``` Your widget entry receives that object as its first argument, the same shape you would pass to `updateAndroidDynamicWidget`: ```tsx export default function PortfolioWidget(props, env) { return ( ${props.total.toFixed(2)} {props.change}% today ) } ``` Check the endpoint with curl before wiring up the widget: ```bash curl "https://api.example.com/widgets/portfolio?widgetId=portfolio&platform=android&theme=dark&locale=en-US" \ -H "Accept: application/json" ``` ### What the response has to be [Section titled “What the response has to be”](#what-the-response-has-to-be) * Status `200` with `Content-Type: application/json` and a JSON **object**. An array, a string, a number or `null` at the top level is rejected. * At most 256 KB. * Return `ETag` and Voltra sends it back as `If-None-Match` on the next fetch. A `304` means the widget keeps what it has and counts as fresh. This applies to widgets with an `entry`; a payload widget’s request is unconditional. * `Cache-Control: max-age=N` moves the next fetch, clamped between 15 minutes and 24 hours. `Retry-After` on a `429` or `503` is honoured the same way. Returning a rendered Voltra payload from an endpoint whose widget has an `entry` is rejected with a log line naming the mismatch. The widget has an entry, so it wants the data, not the picture. ### Telling fresh data from stale [Section titled “Telling fresh data from stale”](#telling-fresh-data-from-stale) The widget is never blanked by a failed fetch: it keeps rendering the last props that arrived, whether from the server or from `updateAndroidDynamicWidget`. `env.serverUpdate` says which: ```tsx export default function PortfolioWidget(props, env) { const stale = env.serverUpdate?.status === 'stale' return ( ${props.total?.toFixed(2) ?? '—'} {env.serverUpdate?.fetchedAt && ( Updated {new Date(env.serverUpdate.fetchedAt).toLocaleTimeString()} )} ) } ``` | Field | Meaning | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `status` | `fresh` after a `200` or `304`; `stale` when a fetch has succeeded before but the last one failed; `never` before the first success; `disabled` while your app has taken the widget over | | `fetchedAt` | Epoch milliseconds of the last `200` or `304`. Absent until a fetch succeeds. | | `error` | `network`, `http`, `unauthorized`, `parse`, or `render`. Absent when `status` is `fresh`. | | `httpStatus` | Status code of the last response, when there was one | `env.serverUpdate` is `undefined` on widgets without a `serverUpdate`. Props that throw during rendering are never committed — Voltra renders them once off screen first, and keeps the previous props when that fails. `env.serverUpdate.error` is `render` while that lasts. ## Authentication [Section titled “Authentication”](#authentication) Widgets on Android are part of the main app binary, so the WorkManager background worker can access credential storage directly. Voltra credentials are encrypted at rest on-device. Note `setWidgetServerCredentials` is deprecated in favour of [`setWidgetServerUpdate`](#changing-settings-at-runtime) with an `Authorization` header, which can also set the URL, the interval, the method, query parameters and a body. Both write the same encrypted records, so switching is a one-line change and nothing has to be migrated on device. ### Setting credentials [Section titled “Setting credentials”](#setting-credentials) Call `setWidgetServerCredentials` after the user logs in: ```typescript import { setWidgetServerCredentials } from '@use-voltra/android-client' await setWidgetServerCredentials({ token: userAccessToken, headers: { 'X-App-Version': '1.0.0', }, }) ``` The `token` is required and is sent as `Authorization: Bearer ` on every server request. Any additional `headers` are also included. If your widget endpoint does not require authentication, skip `setWidgetServerCredentials()` entirely. ### Clearing credentials [Section titled “Clearing credentials”](#clearing-credentials) Call `clearWidgetServerCredentials` when the user logs out: ```typescript import { clearWidgetServerCredentials } from '@use-voltra/android-client' await clearWidgetServerCredentials() ``` All widgets are automatically reloaded after credentials are cleared, so they revert to their default/unauthenticated state immediately. ## Changing settings at runtime [Section titled “Changing settings at runtime”](#changing-settings-at-runtime) `serverUpdate` in `app.json` is the default. Once the app runs it can change any of it, per widget or for all of them, without a rebuild: ```typescript import { setWidgetServerUpdate } from '@use-voltra/android-client' await setWidgetServerUpdate( { url: `https://${tenant}.example.com/widgets/portfolio`, intervalMinutes: 30, headers: { Authorization: `Bearer ${accessToken}` }, }, { widgetId: 'portfolio' } ) ``` | Setting | | | ----------------- | ------------------------------------------------------------------------------------------------------------------------- | | `url` | Must be `https`, or `http` to a local dev host (`localhost`, `127.0.0.1`, `::1`, `10.0.2.2`, `10.0.3.2`) in a debug build | | `intervalMinutes` | Clamped between 15 minutes and 24 hours | | `enabled` | `false` stops fetching until you set it back | | `method` | `GET` (default), `POST`, `PUT`, `PATCH` or `DELETE` | | `query` | Extra query parameters | | `headers` | Extra request headers | | `body` | Sent as `application/json` | Leave out `widgetId` to set the same values for every server-driven widget. A widget-scoped call wins over a global one; `headers` and `query` merge per key across the two, everything else takes the more specific value. Each call replaces everything it set last time, so pass every field you want to keep. Setting anything reschedules the widgets it affects and fetches once straight away. Use this instead of `setWidgetServerCredentials`, which does the same thing for the `Authorization` header alone: ```typescript // Before await setWidgetServerCredentials({ token: accessToken, headers: { 'X-App-Version': '1.0.0' } }) // After await setWidgetServerUpdate({ headers: { Authorization: `Bearer ${accessToken}`, 'X-App-Version': '1.0.0' }, }) ``` To go back to what `app.json` configured, clear the settings: ```typescript import { clearWidgetServerUpdate } from '@use-voltra/android-client' await clearWidgetServerUpdate({ widgetId: 'portfolio' }) await clearWidgetServerUpdate() ``` Clearing the global settings is the logout gesture. Along with the settings it drops what the server last sent — the props and the “updated at” of every server-driven widget — so a Dynamic Widget goes back to rendering `{}` with `env.serverUpdate.status` of `never` rather than showing the previous account’s data. A widget-scoped clear only drops that widget’s overrides and leaves its props alone. Read the settings back with `getWidgetServerUpdate`: ```typescript import { getWidgetServerUpdate } from '@use-voltra/android-client' const snapshot = await getWidgetServerUpdate({ widgetId: 'portfolio' }) if (snapshot?.enabled) { console.log(`portfolio fetches ${snapshot.url} every ${snapshot.intervalMinutes}m`) } ``` With a `widgetId`, this is the fully resolved settings that widget would fetch with right now — every layer flattened and `app.json`’s defaults applied, or `null` if the widget isn’t server-driven. Without one, it’s the raw global layer only: what the last widget-less `setWidgetServerUpdate` call wrote, with no defaults applied, or `null` if nothing has been set globally. Credentials set with the deprecated `setWidgetServerCredentials` are stored separately and are not affected; clear those with `clearWidgetServerCredentials`. Calling either function for a widget that has no `serverUpdate` in `app.json` throws. Whether a widget is server-driven is decided when the native project is generated, so a runtime URL cannot turn a local widget into one — add `serverUpdate` to `app.json` and rebuild. A `body` set alongside `GET` or `HEAD` is dropped with a warning, because neither platform’s HTTP stack can send one. ### Driving a widget from the app [Section titled “Driving a widget from the app”](#driving-a-widget-from-the-app) `updateAndroidWidget` and `updateAndroidDynamicWidget` work on server-driven widgets, but the next scheduled fetch overwrites what you wrote. To keep it, turn fetching off first: ```typescript await setWidgetServerUpdate({ enabled: false }, { widgetId: 'portfolio' }) await updateAndroidDynamicWidget('portfolio', localProps) ``` While fetching is off, `env.serverUpdate.status` is `disabled`, so the widget can hide its “updated N minutes ago” line. Set `enabled: true`, or clear the settings, to hand it back to the server. ## Refresh button [Section titled “Refresh button”](#refresh-button) Server-driven widgets can display a native refresh button that lets users trigger an immediate update on demand. Enable it in your widget config: ```json { "serverUpdate": { "url": "https://api.example.com/widgets/render", "intervalMinutes": 60, "refresh": true } } ``` When enabled, a small circular button (↻) appears in the top-right corner of the widget. On a payload widget, tapping it performs an inline HTTP fetch and pushes the update directly—without waiting for the next scheduled fetch. On a widget with an `entry`, a tap with no signal is queued and retries until it succeeds, rather than failing silently. ## Resize handling [Section titled “Resize handling”](#resize-handling) Your server should return all size variants in every response. When the user resizes a widget on the home screen, Voltra re-renders from cached data—no network request is made. The `RemoteViews(sizeMapping)` mechanism automatically picks the closest matching variant. ## Triggering manual refreshes [Section titled “Triggering manual refreshes”](#triggering-manual-refreshes) You can force-refresh server-driven widgets outside of the regular interval: ```typescript import { reloadAndroidWidgets } from '@use-voltra/android-client' // Reload specific widgets (triggers an immediate WorkManager fetch) await reloadAndroidWidgets(['dynamic_weather']) // Reload all widgets await reloadAndroidWidgets() ``` For server-driven widgets, this enqueues an immediate one-time WorkManager request to fetch fresh content. For local-only widgets, it re-renders from cached data. ## Initial state [Section titled “Initial state”](#initial-state) Server-driven widgets still need content to display before the first server fetch completes. Use `initialStatePath` to provide a pre-rendered default: ```json { "id": "dynamic_weather", "displayName": "Dynamic Weather", "description": "Weather with live server updates", "targetCellWidth": 2, "targetCellHeight": 1, "initialStatePath": "./widgets/android/weather-initial.tsx", "serverUpdate": { "url": "https://api.example.com/widgets/render", "intervalMinutes": 60 } } ``` See [Widget pre-rendering](/android/development/widget-pre-rendering) for details on creating initial state files. Tip Provide a meaningful initial state (e.g. “Loading…” or placeholder content) rather than leaving it empty. The user sees this until the first server fetch succeeds. ## Cross-platform server [Section titled “Cross-platform server”](#cross-platform-server) A single server can handle both iOS and Android requests using `createWidgetUpdateHandler` from `@use-voltra/server`: ```tsx import { Voltra } from '@use-voltra/ios' import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android' import { createWidgetUpdateHandler } from '@use-voltra/server' const handler = createWidgetUpdateHandler({ renderIos: async (req) => { // Return WidgetVariants (systemSmall, systemMedium, etc.) return { systemSmall: Hello } }, renderAndroid: async (req) => { // Return AndroidWidgetVariants (size breakpoints) return [{ size: { width: 200, height: 100 }, content: Hello }] }, validateToken: async (token) => { // Shared token validation for both platforms return verifyJwt(token) }, }) ``` The handler uses the required `platform` query parameter to route requests to the correct render function. If you’re serving the cross-platform endpoint from Node or Express, use `createWidgetUpdateNodeHandler()` or `createWidgetUpdateExpressHandler()` from `@use-voltra/server` instead. ## Error handling and retries [Section titled “Error handling and retries”](#error-handling-and-retries) WorkManager automatically handles failures with exponential backoff. After 5 consecutive failed attempts, the worker gives up to avoid infinite retry loops. The next periodic run will start fresh. * **Network unavailable:** The request is deferred until connectivity is restored (via `NetworkType.CONNECTED` constraint). * **Server errors (non-2xx):** The worker retries with exponential backoff, up to 3 attempts. * **Empty response:** The worker retries with exponential backoff, up to 3 attempts. * **Parse errors:** If the JSON is stored but parsing fails, the data is still saved so Glance can attempt to use it later. This counts as a success since the data is persisted. * **`401` or `403`:** The worker stops rather than backing off — the status will not change until you set a new token, and doing so reloads the widget anyway. For widgets that return props rather than UI, the widget keeps rendering the last props it has through every one of these, and `env.serverUpdate` says what went wrong. # Styling > The React Native style properties Voltra supports on Android and how they map to Jetpack Compose Glance modifiers. You can style Voltra components on Android using React Native-style `style` props. These properties are automatically converted to Jetpack Compose Glance modifiers. For Android system-aware colors, use [`AndroidDynamicColors`](/android/development/dynamic-colors) from `@use-voltra/android` instead of snapshotting palette values in JavaScript. Glance Limitations Android widgets are built using **Jetpack Compose Glance**, which has a significantly more limited styling API compared to standard Compose or SwiftUI. Many common React Native style properties are either not supported or have limited support. ## Supported Properties [Section titled “Supported Properties”](#supported-properties) The following React Native style properties are supported on Android: ### Layout [Section titled “Layout”](#layout) * `width`, `height` - Fixed dimensions (number values in dp) or `"100%"` to fill available space. * `flex`, `flexGrow` - Flex weight. When > 0, the component will take up a proportional amount of space in its parent container (maps to `.defaultWeight()` in Glance). * `padding` - Uniform padding on all edges. * `paddingTop`, `paddingBottom`, `paddingLeft`, `paddingRight` - Individual edge padding. * `paddingHorizontal`, `paddingVertical` - Horizontal and vertical padding. * `visibility` - Controls component visibility (`"visible"`, `"hidden"`, or `"invisible"`). ### Visual Style [Section titled “Visual Style”](#visual-style) * `backgroundColor` - Background color (hex strings, color names, or `AndroidDynamicColors.*` tokens). * `backgroundImage` - CSS gradient background. Supports `linear-gradient(...)`, `radial-gradient(...)`, and `conic-gradient(...)`. * `borderRadius` - Corner radius value. **Note:** Requires Android 12+ (API 31). On older versions, this property is ignored. ### Text [Section titled “Text”](#text) * `fontSize` - Font size in sp. * `fontWeight` - Supports `"normal"` and `"bold"`. * `fontFamily` - Font family name. Built-in values: `"monospace"`, `"serif"`, `"sans-serif"`, `"cursive"`. For custom fonts, see [Custom Fonts](/android/development/custom-fonts). * `color` - Text color (literal colors or `AndroidDynamicColors.*`). * `textDecorationLine` - Supports `"underline"` and `"line-through"`. * `textAlign` - Alignment of text within the component (`"left"`, `"center"`, `"right"`). * `numberOfLines` - Limits the number of lines displayed. ### Image Specific [Section titled “Image Specific”](#image-specific) In addition to general styles, `Image` components support: * `resizeMode` - `"cover"`, `"contain"`, `"stretch"`, `"repeat"`, or `"center"`. * `contentScale` - `"crop"`, `"cover"`, `"fit"`, `"contain"`, `"fill-bounds"`, or `"stretch"`. * `alpha` - Opacity of the image (0.0 to 1.0). * `colorFilter` - Applies a color filter to the image. ## Dynamic colors [Section titled “Dynamic colors”](#dynamic-colors) Android widgets can use semantic Material color roles (`AndroidDynamicColors.*`) so they follow the system palette even when the app isn’t running. See [Dynamic Colors](/android/development/dynamic-colors) for the full role list, examples, and server-rendering behavior. ## Gradient Backgrounds [Section titled “Gradient Backgrounds”](#gradient-backgrounds) Android widgets support gradient backgrounds through the camel-case `style.backgroundImage` property. ```tsx import { VoltraAndroid } from '@use-voltra/android' const element = ( Gradient Widget ) ``` Supported gradient functions are `linear-gradient(...)`, `radial-gradient(...)`, and `conic-gradient(...)`. Repeating gradients, malformed gradients, unsupported color tokens, and invalid stop positions are ignored. If `backgroundColor` is also provided, Android paints it behind transparent gradient pixels and uses it as a fallback when a gradient cannot be rendered. Gradient stops can use Android dynamic color tokens from `AndroidDynamicColors`, but those colors are resolved into the generated bitmap when the widget renders or updates. Existing gradient bitmaps do not recolor until the widget is rendered again. Use `backgroundImage`, not `background-image`. Gradient bitmaps are generated natively during widget rendering and capped before being passed to Glance, so the bitmap does not control layout size. ## Limitations [Section titled “Limitations”](#limitations) The following properties are **NOT supported** on Android due to Glance limitations: * **Margins:** `margin`, `marginTop`, etc. are not part of Android style types. If you need margin-like outside spacing, use `VoltraAndroid.Spacer` between elements. * **Borders:** `borderWidth` and `borderColor` are not yet implemented. * **Shadows:** `shadowColor`, `shadowOffset`, `shadowOpacity`, and `shadowRadius` are not supported. * **Positioning:** Absolute positioning (`top`, `left`, `zIndex`) is not supported. Use stack alignments and spacers. * **Transforms:** `transform` (rotate, scale, etc.) is not supported. * **Opacity:** The general `style.opacity` property is not supported (except for the `alpha` prop on `Image`). * **Dimensions:** `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, and `aspectRatio` are not supported. * **Text Effects:** `letterSpacing`, `fontVariant`, and custom `lineHeight` are not supported. ## Example [Section titled “Example”](#example) ```tsx import { VoltraAndroid } from '@use-voltra/android' const element = ( Android Widget Text ) ``` ## Sharing styles with `StyleSheet` [Section titled “Sharing styles with StyleSheet”](#sharing-styles-with-stylesheet) Widget files can import `StyleSheet` and `Platform` from `react-native`, so styles can live outside the element tree exactly as they do in the rest of your app: ```tsx import { Platform, StyleSheet } from 'react-native' import { VoltraAndroid } from '@use-voltra/android' const styles = StyleSheet.create({ container: { padding: 16, backgroundColor: '#101828', }, title: { color: '#F8FAFC', fontSize: 18, fontWeight: 'bold', }, }) const element = ( {Platform.OS} ) ``` Widget code does not run against the React Native runtime — at build time it is evaluated in a Node sandbox, and Dynamic Widgets run on device in a separate JS engine with no bridge. Only the parts of `react-native` that are pure data manipulation are therefore available: * `StyleSheet.create`, `StyleSheet.flatten`, `StyleSheet.compose`, `StyleSheet.absoluteFill`, `StyleSheet.absoluteFillObject`, and `StyleSheet.hairlineWidth`. * `Platform.OS` and `Platform.select`. Inside a widget, `Platform.OS` is the platform the widget is being built for, so `Platform.select` picks the same branch at build time and on device. Anything else imported from `react-native` — components, `Dimensions`, `Animated`, `PixelRatio` — is rejected with a message naming the symbol. Build steps that evaluate your widget (`voltra apply` and `expo prebuild`) fail outright; a symbol that only appears on a branch those steps never reach throws the same message when the widget renders, rather than reading as `undefined`. Deep imports such as `react-native/Libraries/...` always fail the build. Use the `VoltraAndroid` components for everything visual. # Testing and Previews (Android) > Preview Android widgets inside your app with VoltraWidgetPreview and see how widget picker previews relate to it. Voltra provides multiple ways to preview your Android widgets: 1. **In-App Previews** - Preview layouts within your development app using `VoltraWidgetPreview` 2. **Widget Picker Previews** - Customize what users see in the Android widget picker when adding your widget This page covers in-app previews for development. For widget picker previews, see [Widget Sizing & Previews](/android/api/widget-sizing-and-previews). ## VoltraWidgetPreview [Section titled “VoltraWidgetPreview”](#voltrawidgetpreview) The `VoltraWidgetPreview` component renders Voltra Android JSX content at the exact dimensions of standard Android widget sizes. ### Usage [Section titled “Usage”](#usage) ```tsx import { VoltraAndroid } from '@use-voltra/android' import { VoltraWidgetPreview } from '@use-voltra/android-client' export function MyWidgetPreview() { return ( My Awesome Widget This is how it looks on the home screen! ) } ``` ### Supported Families [Section titled “Supported Families”](#supported-families) Android widgets use responsive sizing. Voltra provides several standard families based on typical grid dimensions: | Family | DP Dimensions | Typical Grid Size | | -------------- | ------------- | ----------------- | | `small` | 150 x 100 | 2x1 | | `mediumSquare` | 200 x 200 | 2x2 | | `mediumWide` | 250 x 150 | 3x2 | | `mediumTall` | 150 x 250 | 2x3 | | `large` | 300 x 200 | 4x2 | | `extraLarge` | 350 x 300 | 4x4 | ## VoltraView (Android) [Section titled “VoltraView (Android)”](#voltraview-android) If you need more control or want to test custom dimensions, you can use the low-level `VoltraView` component. ```tsx import { VoltraAndroid } from '@use-voltra/android' import { VoltraView } from '@use-voltra/android-client' Custom Preview ``` ## Accuracy [Section titled “Accuracy”](#accuracy) The Android preview components use the **actual native Glance renderers** under the hood, so the preview matches production rendering — layout, styling, and component mapping are all identical to what shows on the home screen. Note While layout and styling are accurate, some home-screen specific behaviors (like actual widget resizing by the user) are not simulated by the preview component. # Widget Pre-rendering (Android) > Provide initial widget content at build time with initialStatePath so Android widgets show something before the app first updates them. Widget pre-rendering allows you to provide a meaningful initial state for your Android widgets before they are updated by the app for the first time. ## Configuration [Section titled “Configuration”](#configuration) Add `initialStatePath` to your widget configuration in the `@use-voltra/android-client` plugin in `app.json`: ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "widgets": [ { "id": "weather", "displayName": "Weather Widget", "description": "Shows current weather", "targetCellWidth": 2, "targetCellHeight": 2, "initialStatePath": "./widgets/weather-android-initial.tsx" } ] } ] ] } } ``` For multiple locales, set `initialStatePath` to a map of locale tag → file path (same pattern as iOS); the first-run payload matches the device locale when possible. ## Implementation [Section titled “Implementation”](#implementation) Create a file at the specified `initialStatePath` that exports a default Voltra component (or a React element). For Android, this should use `VoltraAndroid` primitives. ```tsx import { VoltraAndroid } from '@use-voltra/android' const InitialWeatherWidget = ( Loading weather... ) export default InitialWeatherWidget ``` Note `initialStatePath` files are **not** part of your React Native app bundle. They run in Node.js during prebuild. Import `VoltraAndroid` from `@use-voltra/android`, not `@use-voltra/android-client` — the client package pulls in native modules that are unavailable in the prebuild sandbox. ## Limitations [Section titled “Limitations”](#limitations) * **Imports**: Use `@use-voltra/android` for JSX and types in `initialStatePath` files. Do not import from `@use-voltra/android-client` or other React Native client APIs. * **Static Content**: The initial state should represent a “loading” or “offline” state, as it won’t have access to dynamic runtime data until the app runs. # Android Introduction > How Voltra builds Android Home Screen widgets and ongoing notifications from JSX using Jetpack Compose Glance primitives. Voltra lets you build Android Home Screen widgets with JSX. Under the hood it uses Jetpack Compose Glance, and Voltra’s primitives map directly to Glance components. ## Widgets on Android [Section titled “Widgets on Android”](#widgets-on-android) Android widgets have different layout and styling rules compared to iOS Live Activities. While iOS uses SwiftUI-based primitives (VStack, HStack, etc.), Android uses Jetpack Compose Glance primitives (Column, Row, Box). Voltra abstracts these differences where possible, but provides platform-specific namespaces to ensure your UI looks and behaves correctly on each platform. Voltra also exposes Android-specific semantic dynamic colors through `AndroidDynamicColors`, which lets widgets follow the current Material palette without requiring a JavaScript re-render. See [Dynamic Colors](/android/development/dynamic-colors). Voltra also supports Android ongoing notifications for app-driven, persistent status updates. See [Managing Android Ongoing Notifications](/android/development/managing-ongoing-notifications). ### Simple Android Widget [Section titled “Simple Android Widget”](#simple-android-widget) ```tsx import { VoltraAndroid } from '@use-voltra/android' const MyWidget = () => ( Android Widget Powered by Voltra & Glance ) ``` ## Testing and Previews [Section titled “Testing and Previews”](#testing-and-previews) You can preview your Android widgets directly in your app using the `VoltraWidgetPreview` component. This allows for fast iteration without needing to constantly check the home screen. Learn more in the [Testing and Previews guide](/android/development/testing-and-previews). ## Next Steps [Section titled “Next Steps”](#next-steps) Check out the [Setup guide](/android/setup) to set up Voltra for Android. For notification-based experiences, see [Managing Android Ongoing Notifications](/android/development/managing-ongoing-notifications). # Android Setup > Configure the Voltra Expo plugin for Android, run prebuild, and run the app to see your widget in the Android widget picker. Once you have [installed Voltra](/getting-started/installation) for Android, configure the Expo plugin and use `@use-voltra/android` for widget JSX. ## 1. Configure the Expo Plugin [Section titled “1. Configure the Expo Plugin”](#1-configure-the-expo-plugin) Add `@use-voltra/android-client` to your `app.json` or `app.config.js`: ```json { "expo": { "plugins": [ [ "@use-voltra/android-client", { "enableNotifications": true, "widgets": [ { "id": "my_widget", "displayName": "My First Widget", "description": "A simple Voltra widget", "targetCellWidth": 2, "targetCellHeight": 2 } ] } ] ] } } ``` See [Plugin Configuration](/android/api/plugin-configuration) for all options. ## 2. Prebuild for Android [Section titled “2. Prebuild for Android”](#2-prebuild-for-android) Update your native Android project: * npm ```sh npx expo prebuild --platform android ``` * yarn ```sh yarn dlx expo prebuild --platform android ``` * pnpm ```sh pnpm dlx expo prebuild --platform android ``` * bun ```sh bunx expo prebuild --platform android ``` ## 3. Run the app [Section titled “3. Run the app”](#3-run-the-app) ```bash npx expo run:android ``` Your widget should now be available in the Android widget picker! # Installation > Install the Voltra platform packages for JSX primitives and runtime APIs on iOS and Android, plus the optional server packages. Voltra v2 ships as platform packages. In most apps, you install one package for JSX primitives and one package for runtime APIs per platform. ## 1. Install packages [Section titled “1. Install packages”](#1-install-packages) ### iOS (Live Activities and widgets) [Section titled “iOS (Live Activities and widgets)”](#ios-live-activities-and-widgets) * npm ```sh npm install @use-voltra/ios @use-voltra/ios-client ``` * yarn ```sh yarn add @use-voltra/ios @use-voltra/ios-client ``` * pnpm ```sh pnpm add @use-voltra/ios @use-voltra/ios-client ``` * bun ```sh bun add @use-voltra/ios @use-voltra/ios-client ``` ### Android (Home Screen widgets and ongoing notifications) [Section titled “Android (Home Screen widgets and ongoing notifications)”](#android-home-screen-widgets-and-ongoing-notifications) * npm ```sh npm install @use-voltra/android @use-voltra/android-client ``` * yarn ```sh yarn add @use-voltra/android @use-voltra/android-client ``` * pnpm ```sh pnpm add @use-voltra/android @use-voltra/android-client ``` * bun ```sh bun add @use-voltra/android @use-voltra/android-client ``` Use the platform package for JSX primitives: * `@use-voltra/ios` exports `Voltra` * `@use-voltra/android` exports `VoltraAndroid`, `AndroidDynamicColors`, and `AndroidOngoingNotification` Use the client package for React Native runtime APIs: * `@use-voltra/ios-client` exports `startLiveActivity`, `updateWidget`, `VoltraView`, `VoltraWidgetPreview`, and other app-side APIs * `@use-voltra/android-client` exports `updateAndroidWidget`, `requestPinAndroidWidget`, `reloadAndroidWidgets`, `VoltraView`, `VoltraWidgetPreview`, and other app-side APIs ### Server rendering (optional) [Section titled “Server rendering (optional)”](#server-rendering-optional) Use these in your backend or SSR service-not in the React Native app bundle: * **iOS payloads:** `@use-voltra/ios-server` * **Android payloads:** `@use-voltra/android-server` * **Cross-platform widget HTTP handlers:** `@use-voltra/server` Note that pre-render files such as `initialStatePath` should import JSX from `@use-voltra/ios` or `@use-voltra/android` directly, not from the client packages. ## 2. Next Steps [Section titled “2. Next Steps”](#2-next-steps) After installing packages, configure the Voltra Expo plugin for each platform you support: * [Configure iOS Setup](/ios/setup) * [Configure Android Setup](/android/setup) * [Use Voltra in React Native CLI projects](/getting-started/react-native-cli) * [Migrate from v1 to v2](/getting-started/migration-v2) # Introduction > What Voltra is and how it turns JSX into native iOS Live Activities, Dynamic Island layouts, and iOS and Android widgets. Voltra is a library that brings new “platforms” to React Native. Creating features like iOS Live Activities, Dynamic Island layouts, or Android Home Screen Widgets normally requires writing native code in Swift or Kotlin. Voltra changes this by providing a JavaScript-based API and JSX components that get automatically converted to native primitives (SwiftUI on iOS, Jetpack Compose Glance on Android). Here’s how simple it is to create a live activity: ```tsx import { Voltra } from '@use-voltra/ios' import { startLiveActivity } from '@use-voltra/ios-client' const activityUI = ( Driver en route Building A · Lobby pickup Contact driver ) // Start the live activity await startLiveActivity({ lockScreen: activityUI, }) ``` If you prefer using the hook API, check out [`useLiveActivity`](/ios/development/developing-live-activities#useliveactivity) for integrating live activities with the component lifecycle and automatic updates during development. ## Server-side updates via push notifications [Section titled “Server-side updates via push notifications”](#server-side-updates-via-push-notifications) Voltra also supports server-side updates through push notifications. You can use Voltra’s server-side rendering to convert JSX into JSON payloads that you send to devices via Apple’s Push Notification Service (APNS) or Firebase Cloud Messaging (FCM). This enables real-time updates without keeping your app running. The same components you use in your app work on the server: ```tsx import { Voltra, renderLiveActivityToString } from '@use-voltra/ios-server' // Render JSX to JSON payload on your server const payload = renderLiveActivityToString({ lockScreen: ( Driver arrived Ready for pickup ), }) ``` Ready to get started? Head over to the [Installation](/getting-started/installation) guide, or explore platform-specific guides for [iOS](/ios/introduction) and [Android](/android/introduction). # Migration to v2 > Migrate from Voltra v1 to v2: new package names, import mapping, Expo plugin changes, API renames, and pre-render file rules. Voltra v2 introduces two major architectural changes: * The old Voltra umbrella package is gone. Voltra now ships as separate iOS, Android, and server packages. * The native layer moved from Expo Modules to Turbo Modules. Upgrading to v2 requires updating package installs, Expo plugin configuration, and some API usage. This guide walks through those changes. ## Recommended migration order [Section titled “Recommended migration order”](#recommended-migration-order) 1. Replace package installs. 2. Swap the Expo plugin to the platform-specific package. 3. Move JSX imports to `@use-voltra/ios` or `@use-voltra/android`. 4. Move runtime APIs to the matching `*-client` package. 5. Move server rendering code to `@use-voltra/ios-server` or `@use-voltra/android-server`. 6. Rename Android widget APIs that became platform-specific. 7. Verify `initialStatePath` files only import from platform packages. ## What changed [Section titled “What changed”](#what-changed) * **Package split:** old `voltra`, `voltra/client`, `voltra/server`, `voltra/android`, etc. paths are replaced by scoped packages (`@use-voltra/ios`, `@use-voltra/ios-client`, `@use-voltra/ios-server`, `@use-voltra/android`, `@use-voltra/android-client`, `@use-voltra/android-server`, `@use-voltra/server`). * **Platform-specific JSX namespaces:** iOS primitives come from `@use-voltra/ios` as `Voltra`; Android primitives, color tokens, and ongoing notification JSX come from `@use-voltra/android` as `VoltraAndroid`, `AndroidDynamicColors`, and `AndroidOngoingNotification`. * **Client APIs stay in `*-client`:** runtime APIs that run inside the React Native app (starting/updating Live Activities, updating or pinning widgets, preview components, event listeners and hooks) come from `@use-voltra/ios-client` and `@use-voltra/android-client`. * **Server APIs are platform-specific:** use `@use-voltra/ios-server` and `@use-voltra/android-server` for server-side rendering, and `@use-voltra/server` only for cross-platform widget HTTP handlers. See the sections below for exact import diffs. ## Installation changes [Section titled “Installation changes”](#installation-changes) Install the packages that match the layers you use. ### iOS app code [Section titled “iOS app code”](#ios-app-code) * npm ```sh npm install @use-voltra/ios @use-voltra/ios-client ``` * yarn ```sh yarn add @use-voltra/ios @use-voltra/ios-client ``` * pnpm ```sh pnpm add @use-voltra/ios @use-voltra/ios-client ``` * bun ```sh bun add @use-voltra/ios @use-voltra/ios-client ``` ### Android app code [Section titled “Android app code”](#android-app-code) * npm ```sh npm install @use-voltra/android @use-voltra/android-client ``` * yarn ```sh yarn add @use-voltra/android @use-voltra/android-client ``` * pnpm ```sh pnpm add @use-voltra/android @use-voltra/android-client ``` * bun ```sh bun add @use-voltra/android @use-voltra/android-client ``` ### Optional server packages [Section titled “Optional server packages”](#optional-server-packages) * npm ```sh npm install @use-voltra/ios-server @use-voltra/android-server @use-voltra/server ``` * yarn ```sh yarn add @use-voltra/ios-server @use-voltra/android-server @use-voltra/server ``` * pnpm ```sh pnpm add @use-voltra/ios-server @use-voltra/android-server @use-voltra/server ``` * bun ```sh bun add @use-voltra/ios-server @use-voltra/android-server @use-voltra/server ``` ## Import mapping [Section titled “Import mapping”](#import-mapping) ### iOS app code [Section titled “iOS app code”](#ios-app-code-1) ```tsx // v1 import { Voltra } from 'voltra' import { startLiveActivity } from 'voltra/client' // v2 import { Voltra } from '@use-voltra/ios' import { startLiveActivity } from '@use-voltra/ios-client' ``` ### iOS server code [Section titled “iOS server code”](#ios-server-code) ```tsx // v1 import { renderLiveActivityToString, Voltra } from 'voltra/server' // v2 import { Voltra, renderLiveActivityToString } from '@use-voltra/ios-server' ``` ### Android widget code [Section titled “Android widget code”](#android-widget-code) ```tsx // v1 import { VoltraAndroid } from 'voltra/android' import { updateWidget } from 'voltra/android' // v2 import { VoltraAndroid } from '@use-voltra/android' import { updateAndroidWidget } from '@use-voltra/android-client' ``` ### Android server widget code [Section titled “Android server widget code”](#android-server-widget-code) ```tsx // v1 import { createWidgetUpdateNodeHandler } from 'voltra/server' import { AndroidDynamicColors, VoltraAndroid } from 'voltra/android' // v2 import { createAndroidWidgetUpdateNodeHandler } from '@use-voltra/android-server' import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android' ``` ## Expo plugin migration [Section titled “Expo plugin migration”](#expo-plugin-migration) The old docs used a single `voltra` plugin and nested per-platform config. v2 uses platform-specific plugins. ### iOS [Section titled “iOS”](#ios) ```json // v1 { "expo": { "plugins": [ [ "voltra", { "ios": { "groupIdentifier": "group.example.app", "widgets": [] } } ] ] } } // v2 { "expo": { "plugins": [ [ "@use-voltra/ios-client", { "groupIdentifier": "group.example.app", "widgets": [] } ] ] } } ``` ### Android [Section titled “Android”](#android) ```json // v1 { "expo": { "plugins": [ [ "voltra", { "android": { "widgets": [] } } ] ] } } // v2 { "expo": { "plugins": [ [ "@use-voltra/android-client", { "widgets": [] } ] ] } } ``` ## API renames to watch for [Section titled “API renames to watch for”](#api-renames-to-watch-for) * Android widget updates: `updateWidget(...)` -> `updateAndroidWidget(...)` * Android widget reloads: `reloadWidgets(...)` for image-preloading remains, but widget refresh APIs use `reloadAndroidWidgets(...)` * Android widget server handlers: `createWidgetUpdateHandler(...)` style examples should become `createAndroidWidgetUpdateHandler(...)`, `createAndroidWidgetUpdateNodeHandler(...)`, or `createAndroidWidgetUpdateExpressHandler(...)` * iOS widget server handlers: use `createIOSWidgetUpdateHandler(...)`, `createIOSWidgetUpdateNodeHandler(...)`, or `createIOSWidgetUpdateExpressHandler(...)` ## Pre-render files [Section titled “Pre-render files”](#pre-render-files) `initialStatePath` files run in Node during prebuild, not in the React Native runtime. Use: * `@use-voltra/ios` for iOS widget JSX and types * `@use-voltra/android` for Android widget JSX and types Do not import `@use-voltra/ios-client` or `@use-voltra/android-client` from pre-render files. ## After migrating [Section titled “After migrating”](#after-migrating) Re-run prebuild for any platform whose plugin configuration changed: ```bash npx expo prebuild --platform ios npx expo prebuild --platform android ``` # Prior Art > The open-source libraries and projects that inspired Voltra's approach to bridging JavaScript and native Live Activities. Voltra wouldn’t be possible without the incredible work of the open-source community. This page acknowledges the libraries and projects that inspired and informed our approach to bridging JavaScript and native iOS Live Activities. ## Inspiration [Section titled “Inspiration”](#inspiration) ### Dynamic UI [Section titled “Dynamic UI”](#dynamic-ui) The core concept of describing SwiftUI layouts through JSON configuration was pioneered by Wesley de Groot’s [Dynamic UI](https://github.com/0xWDG/DynamicUI). ### Expo Live Activity [Section titled “Expo Live Activity”](#expo-live-activity) The insight of combining JavaScript-driven development with iOS Live Activities came from Software Mansion’s [Expo Live Activity](https://github.com/software-mansion-labs/expo-live-activity). Referencing their open-source Expo config plugin logic was helpful during early development. ### Expo Widgets [Section titled “Expo Widgets”](#expo-widgets) Voltra spawns a secondary JS runtime to drive native widget and Live Activity rendering. That’s not just a theoretical option — Expo’s own [`expo-widgets`](https://docs.expo.dev/versions/latest/sdk/widgets/) module does the same thing in production: when the system asks for a widget timeline or starts a Live Activity, your component runs in a separate JS runtime and produces a native layout tree. Seeing this pattern work at Expo SDK scale, across both iOS and Android, was a strong signal that it’s a practical foundation to build on, not just a corner case. ## Thank You [Section titled “Thank You”](#thank-you) We extend our gratitude to the following organizations and individuals: * **Wesley de Groot** for creating Dynamic UI and demonstrating the power of JSON-driven SwiftUI interfaces. * **Software Mansion** for open-sourcing their Expo Live Activity library. * **Expo** for building Expo Modules that power Voltra behind the scenes. * **The broader open-source community** for all the libraries, tools, and ideas that make innovative projects like Voltra possible in the first place. Voltra is our contribution back to the broader React Native community. We hope it helps developers create more engaging and interactive Live Activities and Widgets for their iOS applications. *** *If you’re working on something that builds upon Voltra, we’d love to hear about it! Feel free to reach out and let us know how you’re using it.* # React Native CLI Projects > Use Voltra in React Native CLI projects with the voltra CLI and voltra.config.ts instead of Expo config plugins. Voltra fully supports React Native CLI projects through the `voltra` CLI. Instead of relying on Expo config plugins, `voltra apply` updates the native project for you: it modifies the files Voltra needs, generates new Voltra-owned files, and cleans up outdated generated files from previous runs. ## Installation [Section titled “Installation”](#installation) Install the same native Voltra packages you would use in Expo for the platforms you support, then add `voltra` as a dev dependency. ### iOS [Section titled “iOS”](#ios) * npm ```sh npm install @use-voltra/ios @use-voltra/ios-client ``` * yarn ```sh yarn add @use-voltra/ios @use-voltra/ios-client ``` * pnpm ```sh pnpm add @use-voltra/ios @use-voltra/ios-client ``` * bun ```sh bun add @use-voltra/ios @use-voltra/ios-client ``` ### Android [Section titled “Android”](#android) * npm ```sh npm install @use-voltra/android @use-voltra/android-client ``` * yarn ```sh yarn add @use-voltra/android @use-voltra/android-client ``` * pnpm ```sh pnpm add @use-voltra/android @use-voltra/android-client ``` * bun ```sh bun add @use-voltra/android @use-voltra/android-client ``` ### Voltra CLI [Section titled “Voltra CLI”](#voltra-cli) * npm ```sh npm install -D voltra ``` * yarn ```sh yarn add -D voltra ``` * pnpm ```sh pnpm add -D voltra ``` * bun ```sh bun add -D voltra ``` Then create a `voltra.config.ts` file. Most properties under `ios` and `android` are the same as the Expo config equivalents (see [Configuration](#configuration) below). Minimal example: ```ts import type { VoltraConfig } from 'voltra' const config: VoltraConfig = { ios: { // Commonly needed on iOS so the app and extension can share data. groupIdentifier: 'group.com.example.app', widgets: [ { // Basic widget identity fields. id: 'portfolio', displayName: 'Portfolio', description: 'Track holdings', // Optional, but commonly used for build-time initial widget content. initialStatePath: './widgets/portfolio.ios.tsx', }, ], }, android: { widgets: [ { id: 'portfolio', displayName: 'Portfolio', description: 'Track holdings', // Required on Android. targetCellWidth: 2, targetCellHeight: 2, initialStatePath: './widgets/portfolio.android.tsx', }, ], }, } export default config ``` Once the config is in place, apply the native project changes: * npm ```sh npx voltra apply ``` * yarn ```sh yarn voltra apply ``` * pnpm ```sh pnpm voltra apply ``` * bun ```sh bunx voltra apply ``` ## Configuration [Section titled “Configuration”](#configuration) Most properties under `ios` and `android` use the same names as the Expo config equivalents: * [iOS Expo config options](/ios/api/plugin-configuration) * [Android Expo config options](/android/api/plugin-configuration) The properties below are specific to the Voltra CLI: | Property | Purpose | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `projectRoot` | Overrides the root directory Voltra should treat as the native project root. Useful when the config file does not live at the app root. | | `ios.userImagesPath` | Overrides the directory for user-provided iOS widget images. | | `ios.project` | Lets you override iOS project discovery when the app does not use the standard React Native layout. Supports fields such as `rootDir`, `xcodeprojPath`, `mainTargetName`, `infoPlistPath`, `entitlementsPath`, and `podfilePath`. See [Multiple environments](#multiple-environments) for setting `entitlementsPath` per build configuration. | | `android.userImagesPath` | Overrides the directory for user-provided Android widget images. | | `android.project` | Lets you override Android project discovery when the app does not use the standard React Native layout. Supports fields such as `rootDir`, `appModuleName`, `manifestPath`, and `packageName`. | For the full config shape, see [`VoltraConfig` and related types in source](https://github.com/callstackincubator/voltra/blob/main/packages/cli/src/config/types.ts). ## Multiple environments [Section titled “Multiple environments”](#multiple-environments) Apps that ship several environments — dev, test, staging, production — build them from one Xcode project using a build configuration per environment, and each environment usually needs its own App Group so a dev build cannot read the production widget’s data. `ios.groupIdentifier`, `ios.keychainGroup` and `ios.project.entitlementsPath` accept one value per Xcode build configuration name for that: ```ts ios: { groupIdentifier: { Debug: 'group.com.example.app.dev', ReleaseStaging: 'group.com.example.app.staging', Release: 'group.com.example.app', }, } ``` The keys are Xcode **build configuration** names, not scheme names. A scheme selects a build configuration per action, so a scheme that runs `Debug` and archives `Release` picks up the value for whichever configuration the build uses. Every build configuration of the app target must have a value; `voltra apply` lists the project’s configurations if one is missing or misspelled. For `groupIdentifier` and `keychainGroup`, `voltra apply` writes the map into your Xcode project as a `VOLTRA_*` user-defined build setting holding one value per configuration, then writes a reference to that setting — not the value itself — into the entitlements and `Info.plist` files. Both the app and the generated widget extension inherit the setting, so each build picks up the value for the configuration it is built with. Voltra adds, updates, and removes these settings as your config changes; do not define your own settings under the `VOLTRA_` prefix. If you already keep environment values in `.xcconfig` files, pass a plain string referencing your own build setting instead, and Voltra copies it through verbatim: ```ts ios: { groupIdentifier: '$(MY_APP_GROUP)', } ``` `ios.project.entitlementsPath` works differently: it does not create a `VOLTRA_*` setting. Most projects need no config at all — when a build configuration already points at its own `.entitlements` file, `voltra apply` discovers it and writes the App Group in directly. Set `entitlementsPath` per build configuration only when a file cannot be discovered; each path is then written as that configuration’s `CODE_SIGN_ENTITLEMENTS` on the app target. ## Using Voltra CLI [Section titled “Using Voltra CLI”](#using-voltra-cli) Every time you change `voltra.config.ts`, reapply the native project changes (see the command above). The JSX APIs and runtime APIs are the same as in the rest of the Voltra docs. Once `voltra apply` has set up your native project, continue with the platform guides for [iOS](/ios/introduction) and [Android](/android/introduction). # Configuration > Reference for the options passed when starting, updating, or ending a Live Activity, including dismissal policy and stale dates. Voltra provides several configuration options to control Live Activity behavior, lifecycle, and appearance. These options can be used when starting, updating, or stopping Live Activities. For Expo plugin configuration options (like `groupIdentifier`, `enablePushNotifications`, `deploymentTarget`, and `widgets`), see the [Plugin Configuration](/ios/api/plugin-configuration) documentation. ## Dismissal Policy [Section titled “Dismissal Policy”](#dismissal-policy) Voltra supports configuring how Live Activities behave after they end. You can control the dismissal timing using the `dismissalPolicy` option: ### Dismissal Policy Options [Section titled “Dismissal Policy Options”](#dismissal-policy-options) * **`'immediate'`** (default): The Live Activity is dismissed immediately when it ends * **`{ after: number }`**: The Live Activity remains visible for the specified number of seconds after ending, then automatically dismisses ### Usage Examples [Section titled “Usage Examples”](#usage-examples) **Immediate dismissal (default behavior):** ```typescript import { startLiveActivity } from '@use-voltra/ios-client' await startLiveActivity(variants, { dismissalPolicy: 'immediate', // or omit for default }) ``` **Delayed dismissal (keep visible for 30 seconds after ending):** ```typescript await startLiveActivity(variants, { dismissalPolicy: { after: 30 }, }) ``` **Update dismissal policy for active Live Activities:** ```typescript import { updateLiveActivity } from '@use-voltra/ios-client' await updateLiveActivity(activityId, variants, { dismissalPolicy: { after: 60 }, }) ``` **Set dismissal policy when ending a Live Activity:** ```typescript import { stopLiveActivity } from '@use-voltra/ios-client' await stopLiveActivity(activityId, { dismissalPolicy: { after: 10 }, }) ``` The dismissal policy applies to both programmatic ending (`stopLiveActivity`) and natural ending (when timers reach their end time). This gives you fine-grained control over the user experience when Live Activities conclude. ## Additional Configuration Options [Section titled “Additional Configuration Options”](#additional-configuration-options) ### Stale Date [Section titled “Stale Date”](#stale-date) The `staleDate` option allows you to specify when a Live Activity should be considered stale and automatically dismissed by the system. ```typescript import { startLiveActivity } from '@use-voltra/ios-client' // Dismiss the Live Activity after 1 hour await startLiveActivity(variants, { staleDate: Date.now() + 60 * 60 * 1000, // 1 hour from now }) ``` **Note:** If you provide a `staleDate` in the past, it will be ignored and the Live Activity will use default behavior. ### Relevance Score [Section titled “Relevance Score”](#relevance-score) The `relevanceScore` option helps iOS prioritize which Live Activities to display when space is limited. Higher scores (closer to 1.0) indicate more important activities. ```typescript import { startLiveActivity } from '@use-voltra/ios-client' // High priority Live Activity (e.g., active delivery) await startLiveActivity(variants, { relevanceScore: 0.8, }) // Low priority Live Activity (e.g., background task) await startLiveActivity(variants, { relevanceScore: 0.2, }) ``` **Valid range:** 0.0 to 1.0 (default: 0.0) ### Channel ID (broadcast push, iOS 18+) [Section titled “Channel ID (broadcast push, iOS 18+)”](#channel-id-broadcast-push-ios-18) The `channelId` option subscribes the Live Activity to a broadcast channel for server-side updates. When provided, the activity receives updates via broadcast push notifications instead of individual device tokens—one server notification updates all activities on that channel. Requires `enablePushNotifications: true` and the Broadcast Capability enabled in your Apple Developer account. ```typescript import { startLiveActivity } from '@use-voltra/ios-client' await startLiveActivity(variants, { activityName: 'match-123', channelId: 'CTrNsYq/Ee8AALLzHQaVlA==', // From APNs channel management }) ``` For full broadcast setup, see [Server-side updates - Broadcast push notifications](/ios/development/server-side-updates#broadcast-push-notifications-ios-18). These options can be used together with dismissal policy and other configuration options: ```typescript await startLiveActivity(variants, { dismissalPolicy: { after: 30 }, staleDate: Date.now() + 2 * 60 * 60 * 1000, // 2 hours relevanceScore: 0.7, }) ``` # Plugin configuration > Reference for the iOS Voltra Expo plugin options: groupIdentifier, enablePushNotifications, liveActivities, deploymentTarget, and widgets. The Voltra Expo config plugin accepts several configuration options in your `app.json` or `app.config.js`: ```json { "expo": { "plugins": [ [ "@use-voltra/ios-client", { "groupIdentifier": "group.your.bundle.identifier", "enablePushNotifications": true, "deploymentTarget": "18.0", "targetName": "MyAppLiveActivity", "widgets": [ { "id": "weather", "displayName": "Weather Widget", "description": "Shows current weather conditions", "supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"], "initialStatePath": "./widgets/weather-initial.tsx" } ] } ] ] } } ``` ## Configuration options [Section titled “Configuration options”](#configuration-options) ### `groupIdentifier` (optional) [Section titled “groupIdentifier (optional)”](#groupidentifier-optional) App Group identifier for sharing data between your app and the widget extension. Required if you want to: * Forward component events (like button taps) from Live Activities to your JavaScript code * Share images between your app and the extension * Use image preloading features * Update entry-based Dynamic Widgets with runtime props * Use Dynamic Live Activities **Format:** Must start with `group.` (e.g., `group.your.bundle.identifier`) ### `enablePushNotifications` (optional) [Section titled “enablePushNotifications (optional)”](#enablepushnotifications-optional) Enable server-side updates for Live Activities via Apple Push Notification Service (APNS). When enabled, you can update Live Activities even when your app is in the background or terminated. **Type:** `boolean`\ **Default:** `false` ### `liveActivities` (optional) [Section titled “liveActivities (optional)”](#liveactivities-optional) Bundled Dynamic Live Activity definitions. Every declaration has a stable `id` and an `entry` module that default-exports the renderer function. IDs use only alphanumeric characters and underscores, and are unique within this collection; they are separate from Dynamic Widget IDs. When this array is non-empty, `groupIdentifier` is required. See [Dynamic Live Activities](/ios/development/dynamic-live-activities) for the entry signature, lifecycle APIs, and push payload contract. ### `deploymentTarget` (optional) [Section titled “deploymentTarget (optional)”](#deploymenttarget-optional) iOS deployment target version for the widget extension. If not provided, defaults to `17.0`. This allows the widget extension to have its own deployment target independent of the main app. **Type:** `string` **Default:** `"17.0"` **Example:** `"18.0"` **Note:** Code signing settings (development team, provisioning profiles) are automatically synchronized from the main app target, but the deployment target can be set independently. ### `targetName` (optional) [Section titled “targetName (optional)”](#targetname-optional) Custom target name for the widget extension. If not provided, defaults to `{AppName}LiveActivity` where `AppName` is your app’s sanitized name. Useful for matching existing provisioning profiles, credentials, or naming conventions (e.g., when migrating from `@bacons/apple-targets`). **Type:** `string` **Default:** `"{AppName}LiveActivity"` **Example:** `"widget"`, `"MyAppLiveActivity"` ```json { "expo": { "plugins": [ [ "@use-voltra/ios-client", { "groupIdentifier": "group.your.bundle.identifier", "targetName": "widget" } ] ] } } ``` ### `widgets` (optional) [Section titled “widgets (optional)”](#widgets-optional) Array of widget configurations for Home Screen widgets. Each widget will be available in the iOS widget gallery. **Widget Configuration Properties:** * `id`: Unique identifier for the widget (alphanumeric with underscores only) * `displayName`: Name shown in the widget gallery (plain string, or per-locale map like `{ "en": "Weather", "pl": "Pogoda" }`; locale keys are BCP‑47-style tags) * `description`: Description shown in the widget gallery (same localization rules as `displayName`) * `kind` (optional): WidgetKit kind of the widget. Defaults to `Voltra_Widget_`; see [Keeping the kind of an existing widget](#keeping-the-kind-of-an-existing-widget) * `supportedFamilies`: Array of supported widget sizes (`systemSmall`, `systemMedium`, `systemLarge`) * `initialStatePath`: (optional) Project-relative path to a file that exports initial widget state, **or** a locale map of paths for localized build-time pre-rendering (see [Widget Pre-rendering](/ios/development/widget-pre-rendering)) * `serverUpdate`: (optional) Fetch the widget’s content on a schedule. Without `entry` the server returns a rendered payload; with `entry` it returns plain JSON that the widget renders on the device. `url` is optional — leave it out to supply one at runtime. See [Server-driven widgets](/ios/development/server-driven-widgets) for full details. * `url`: The Voltra SSR endpoint URL * `intervalMinutes`: Update interval in minutes (default: `15`) * `refresh`: Show a native refresh button (default: `false`, requires iOS 17+) * `appIntent`: (optional, Dynamic Widgets, iOS 17+) Parameters the user edits in the Edit Widget sheet. Each parameter has a `name`, a `title` (plain string or locale map), an optional `default`, and optional `options` (`[{ "value": "metric", "title": "Metric" }]`) that turn the field into a picker. See [Configurable Widgets](/ios/development/configurable-widgets) **Example:** ```json { "widgets": [ { "id": "weather", "displayName": "Weather Widget", "description": "Current weather conditions", "supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"], "initialStatePath": { "en": "./widgets/weather-initial.tsx", "pl": "./widgets/weather-initial-pl.tsx" }, "serverUpdate": { "url": "https://api.example.com/widgets/render", "intervalMinutes": 30, "refresh": true } } ] } ``` ### Keeping the kind of an existing widget [Section titled “Keeping the kind of an existing widget”](#keeping-the-kind-of-an-existing-widget) WidgetKit identifies a widget placed on the Home Screen by its extension bundle identifier and its `kind`. When you migrate an existing WidgetKit widget to Voltra, keep both so users don’t have to remove and re-add the widget: set `targetName` to the name of your existing extension target and `kind` to the `kind` your `WidgetConfiguration` used. ```json { "targetName": "MyWidgets", "widgets": [ { "id": "streak", "kind": "StreakWidget", "displayName": "Streak", "description": "Your daily streak" } ] } ``` The `id` stays the handle you use from JavaScript (`updateWidget('streak', ...)`), only the WidgetKit kind changes. Kinds must be unique across widgets. This works the same way in `voltra.config.ts` when you use the [React Native CLI setup](/getting-started/react-native-cli). ### Localizing `displayName` and `description` [Section titled “Localizing displayName and description”](#localizing-displayname-and-description) Use a locale map when the widget gallery label should be translated: ```json { "widgets": [ { "id": "weather", "displayName": { "en": "Weather", "pl": "Pogoda", "zh-Hans": "天气" }, "description": { "en": "Current weather conditions", "pl": "Aktualne warunki pogodowe", "zh-Hans": "当前天气状况" } } ] } ``` Use BCP-47-style locale tags such as `en`, `en-US`, `pt-BR`, or `zh-Hans`. Fallback behavior: * Voltra first tries the device locale. * If there is no exact match, it falls back to the language-only match. * If there is still no match, it prefers an English locale such as `en` or `en-US`. * If no English entry exists, it uses the first configured locale. ### Languages widgets can use [Section titled “Languages widgets can use”](#languages-widgets-can-use) Widgets declare the same languages as the app, so `env.locale` resolves to the same language the app runs in. The list comes from the Expo `locales` config keys, `ios.infoPlist.CFBundleLocalizations`, every locale used in a widget locale map, and the app’s development language (`ios.infoPlist.CFBundleDevelopmentRegion`, otherwise `en`). A language missing from this list is never used for `env.locale`, even when the user prefers it. See [Localization](/ios/development/localization#declare-the-languages-your-app-supports). # Charts (iOS) > Build bar, line, area, point, rule, and sector charts in iOS Live Activities and widgets with Voltra.Chart and its mark components. Use charts in Live Activities and widgets to show trends, comparisons, progress, or composition at a glance. You can mix bars, lines, areas, points, rules, and sectors in a single chart. Note Charts require iOS 16.0+. SectorMark (pie/donut) requires iOS 17.0+. Caution Mark components (`BarMark`, `LineMark`, etc.) must be **direct children** of ``. They cannot be wrapped in custom components. For example, this will not work: ```tsx // This won't work — marks are not direct children function MyMarks() { return } ``` Instead, always place marks directly inside Chart: ```tsx ``` ## Basic Usage [Section titled “Basic Usage”](#basic-usage) Wrap one or more mark components inside ``: ```tsx ``` ## Data Types [Section titled “Data Types”](#data-types) All marks except `RuleMark` take a `data` prop. There are two data shapes depending on the mark type: ```typescript // BarMark, LineMark, AreaMark, PointMark type ChartDataPoint = { x: string | number // Categorical ("Jan") or numeric (42) y: number series?: string // Optional — groups data for multi-series charts } // SectorMark type SectorDataPoint = { value: number // Proportional angular value category: string // Sector label } ``` ## Marks [Section titled “Marks”](#marks) ### BarMark [Section titled “BarMark”](#barmark) Use bars when people need to compare values across categories. **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Fill color. * `cornerRadius` (number, optional): Rounded bar corners. * `width` (number, optional): Fixed bar width. * `stacking` (string, optional): `"grouped"` (side by side). ```tsx ``` *** ### LineMark [Section titled “LineMark”](#linemark) Use a line when the shape of change matters more than individual columns. **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Line color. * `lineWidth` (number, optional): Stroke width in points. * `interpolation` (string, optional): Curve type — `"linear"`, `"monotone"`, `"catmullRom"`, `"cardinal"`, `"stepStart"`, `"stepCenter"`, or `"stepEnd"`. * `symbol` (string, optional): Symbol at each point — `"circle"`, `"square"`, `"triangle"`, `"diamond"`, `"pentagon"`, `"cross"`, `"plus"`, or `"asterisk"`. ```tsx ``` *** ### AreaMark [Section titled “AreaMark”](#areamark) Use an area chart when you want the overall volume or rise/fall pattern to read quickly. **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Fill color. * `interpolation` (string, optional): Same options as LineMark. ```tsx ``` *** ### PointMark [Section titled “PointMark”](#pointmark) Use points for sparse measurements, scatter plots, or to emphasize exact observations. **Parameters:** * `data` (ChartDataPoint\[], required): The data points. * `color` (string, optional): Point color. * `symbol` (string, optional): Same options as LineMark. * `symbolSize` (number, optional): Symbol size in points. ```tsx ``` *** ### RuleMark [Section titled “RuleMark”](#rulemark) A horizontal or vertical reference line. Unlike other marks, RuleMark has no `data` array. **Parameters:** * `yValue` (number, optional): Draw a horizontal line at this y value. * `xValue` (string | number, optional): Draw a vertical line at this x value. * `color` (string, optional): Line color. * `lineWidth` (number, optional): Stroke width in points. If both `xValue` and `yValue` are provided, Voltra renders both lines. ```tsx ``` *** ### SectorMark [Section titled “SectorMark”](#sectormark) Pie and donut charts. Requires iOS 17+. **Parameters:** * `data` (SectorDataPoint\[], required): Sector data with `value` and `category`. * `color` (string, optional): Fill color (overrides automatic coloring). * `innerRadius` (number, optional): Ratio from 0 to 1. `0` = pie chart, any value above `0` = donut chart. * `outerRadius` (number, optional): Ratio from 0 to 1. * `angularInset` (number, optional): Gap between sectors in degrees. ```tsx // Pie chart // Donut chart ``` ## Chart Props [Section titled “Chart Props”](#chart-props) The `` container accepts these props in addition to the standard Voltra `style` prop: | Prop | Type | Description | | ---------------------- | ---------------------------------------------------------------------------- | --------------------------------------- | | `xAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the x-axis | | `xAxisGridStyle` | `{ visible?: boolean; color?: string; lineWidth?: number; dash?: number[] }` | Control x-axis grid lines | | `yAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the y-axis | | `yAxisGridStyle` | `{ visible?: boolean; color?: string; lineWidth?: number; dash?: number[] }` | Control y-axis grid lines | | `legendVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the legend | | `foregroundStyleScale` | `Record` | Map series names to colors | | `yScale` | `{ min?: number; max?: number }` | Pin the y-axis lower and/or upper bound | ## Value Range [Section titled “Value Range”](#value-range) By default the y-axis follows the data. Use `yScale` when a chart needs a fixed window instead — a percentage that should always read against 100, or a series whose swings you want to keep comparable between updates: ```tsx ``` Either bound can stand alone. `yScale={{ min: 0 }}` keeps the baseline at zero and lets the top follow the data, which is the usual way to stop a line chart from exaggerating small changes. Values outside the pinned range are clipped to the plot. ## Grid Lines [Section titled “Grid Lines”](#grid-lines) Use `xAxisGridStyle` and `yAxisGridStyle` when the default grid is too busy or not visible enough for your design: ```tsx ``` ## Multi-Series Charts [Section titled “Multi-Series Charts”](#multi-series-charts) Add a `series` field to your data points when you want multiple datasets in the same chart. Use `foregroundStyleScale` to keep those series colors consistent: ```tsx ``` Without `foregroundStyleScale`, colors are chosen automatically. For side-by-side bars, set `stacking="grouped"`: ```tsx ``` ## Combining Marks [Section titled “Combining Marks”](#combining-marks) Mix mark types when one chart needs both context and emphasis, such as bars for totals plus a rule for a target: ```tsx ``` ## Sparkline / Minimal Style [Section titled “Sparkline / Minimal Style”](#sparkline--minimal-style) Hide axes and legend for a clean, compact visualization: ```tsx ``` ## Widget / Live Activity Notes [Section titled “Widget / Live Activity Notes”](#widget--live-activity-notes) Charts in widgets and Live Activities are static. Focus on a clear snapshot of the data rather than interactions like panning or scrolling. The `` component supports the full Voltra style system on its container — padding, background, borders, corner radius, shadows, and sizing all work: ```tsx ``` # Interactive Controls (iOS) > Reference for Voltra iOS interactive components: Button, Link, and Toggle, which trigger events or open URLs from Live Activities. User interface controls that respond to user interaction in Live Activities. *** ## Button [Section titled “Button”](#button) An interactive button component that triggers in-app events via interaction intents. **Parameters:** * `buttonStyle` (string, optional): Visual style of the button: * `"automatic"` - System-determined style * `"bordered"` - Bordered style * `"borderedProminent"` - Bordered with prominent fill * `"plain"` - Plain style without border * `"borderless"` - Borderless style **Apple Documentation:** [Button](https://developer.apple.com/documentation/swiftui/button) **Availability:** iOS 17.0+ (interaction intents) ### Usage [Section titled “Usage”](#usage) Buttons fire interaction events that you can handle in your app: ```tsx Play Music ``` Handle the event: ```typescript import { addVoltraListener } from '@use-voltra/ios-client' const subscription = addVoltraListener('interaction', (event) => { if (event.identifier === 'play-button') { // Handle play action } }) ``` ### Examples [Section titled “Examples”](#examples) **Basic button:** ```tsx Save Changes ``` **Button with icon:** ```tsx Delete ``` *** ## Link [Section titled “Link”](#link) A navigable link component that opens a URL when tapped. Uses SwiftUI’s native Link for semantic navigation. **Parameters:** * `destination` (string, required): URL to navigate to when tapped. Supports both absolute URLs and relative paths. **Apple Documentation:** [Link](https://developer.apple.com/documentation/swiftui/link) **Availability:** iOS 14.0+ ### URL Normalization [Section titled “URL Normalization”](#url-normalization) Link automatically normalizes URLs using your app’s URL scheme: * Absolute URLs: Used as-is (`"myapp://orders/123"`, `"https://example.com"`) * Relative with `/`: `"/settings"` → `"myapp://settings"` * Relative without `/`: `"help"` → `"myapp://help"` ### Examples [Section titled “Examples”](#examples-1) **Link with absolute URL:** ```tsx Order #123 Tap to view details ``` **Link with relative path:** ```tsx Open Settings ``` ### When to use Link vs Button [Section titled “When to use Link vs Button”](#when-to-use-link-vs-button) | Feature | Link | Button | | ---------------- | ------------------------------ | ------------------------------------------ | | **Use Case** | Navigation to URLs | In-app actions/events | | **Visual** | Unstyled (custom via children) | Button styling (bordered, prominent, etc.) | | **iOS Version** | 14.0+ | 17.0+ | | **Tap Behavior** | Opens URL | Fires interaction event | | **Mechanism** | SwiftUI Link | AppIntents (VoltraInteractionIntent) | *** ## Toggle [Section titled “Toggle”](#toggle) Toggles a boolean state via an intent. Fires an interaction event when changed. **Parameters:** * `defaultValue` (boolean, optional): Initial toggle state (default: `false`) **Apple Documentation:** [Toggle](https://developer.apple.com/documentation/swiftui/toggle) **Availability:** iOS 17.0+ **Example:** ```tsx ``` Handle toggle events: ```typescript import { addVoltraListener } from '@use-voltra/ios-client' const subscription = addVoltraListener('interaction', (event) => { if (event.identifier === 'notifications-toggle') { // Handle toggle state change } }) ``` # Layout & Containers (iOS) > Reference for Voltra iOS layout components: stacks, alignment and offsets, View, Spacer, and other containers that arrange child elements. Components that arrange other elements or provide structural grouping. ## Alignment & Positioning [Section titled “Alignment & Positioning”](#alignment--positioning) Voltra uses SwiftUI’s native positioning model. Instead of CSS-style `position: absolute` with `top`/`left`/`right`/`bottom`, you use: 1. **Stack `alignment` props** - Position children within their container 2. **`offsetX`/`offsetY` styles** - Fine-tune individual element positions after alignment (positive `offsetX` moves right, positive `offsetY` moves down) Each stack type has different alignment options based on its layout direction. *** ### VStack [Section titled “VStack”](#vstack) A vertical stack container that arranges its children in a column. **Parameters:** * `spacing` (number, optional): Spacing between children in points * `alignment` (string, optional): Horizontal alignment of children: * `"leading"` - Align to left edge * `"center"` (default) - Align to center * `"trailing"` - Align to right edge **Apple Documentation:** [VStack](https://developer.apple.com/documentation/swiftui/vstack) *** ### HStack [Section titled “HStack”](#hstack) A horizontal stack container that arranges its children in a row. **Parameters:** * `spacing` (number, optional): Spacing between children in points * `alignment` (string, optional): Vertical alignment of children: * `"top"` - Align to top edge * `"center"` (default) - Align to center * `"bottom"` - Align to bottom edge * `"firstTextBaseline"` - Align to first text baseline * `"lastTextBaseline"` - Align to last text baseline **Apple Documentation:** [HStack](https://developer.apple.com/documentation/swiftui/hstack) *** ### ZStack [Section titled “ZStack”](#zstack) A depth-based stack container that overlays its children on top of each other. Use ZStack when you need to layer elements, such as placing a badge over an image. **Parameters:** * `alignment` (string, optional): Positions ALL children at the specified alignment point. Available values: * `"center"` (default) - Center of the stack * `"leading"` - Left edge (or right in RTL) * `"trailing"` - Right edge (or left in RTL) * `"top"` - Top edge * `"bottom"` - Bottom edge * `"topLeading"` - Top-left corner * `"topTrailing"` - Top-right corner * `"bottomLeading"` - Bottom-left corner * `"bottomTrailing"` - Bottom-right corner **Apple Documentation:** [ZStack](https://developer.apple.com/documentation/swiftui/zstack) #### Positioning with ZStack [Section titled “Positioning with ZStack”](#positioning-with-zstack) **Example: Badge overlay** ```tsx {/* Image defines the ZStack size */} {/* Badge is positioned at top-right, then nudged with offset */} 3 ``` *** ### View [Section titled “View”](#view) A flexible container that **always uses flexbox layout**, unlike VStack and HStack which use native SwiftUI stacks. See the [Flexbox Layout](/ios/development/flexbox-layout) guide for details. **Style Properties:** View responds to flexbox style properties set via the `style` prop: * `flexDirection`: `'row'` | `'column'` (default: `'column'`) * `alignItems`: `'flex-start'` | `'center'` | `'flex-end'` | `'stretch'` * `justifyContent`: `'flex-start'` | `'center'` | `'flex-end'` | `'space-between'` | `'space-around'` | `'space-evenly'` * `gap`: Spacing between children in points **Example:** ```tsx // Horizontal layout with space between Left Center Right // Vertical layout with centered items Success ``` **When to use View:** * You need React Native-style flexbox behavior * You want dynamic `flexDirection` (switching between row/column) * You need `justifyContent` spacing modes **When to use VStack/HStack:** * Simple vertical or horizontal layouts * You want SwiftUI’s native stack performance * You need SwiftUI-specific alignment (like firstTextBaseline) **Availability:** iOS 16.0+ **Learn More:** [Flexbox Layout Guide](/ios/development/flexbox-layout) *** ### Spacer [Section titled “Spacer”](#spacer) A flexible space component that expands to fill available space in its container. **Parameters:** * `minLength` (number, optional): Minimum length **Apple Documentation:** [Spacer](https://developer.apple.com/documentation/swiftui/spacer) *** ### GroupBox [Section titled “GroupBox”](#groupbox) A grouped content container that visually groups related content with a styled background. **Parameters:** None **Apple Documentation:** [GroupBox](https://developer.apple.com/documentation/swiftui/groupbox) *** ### GlassContainer [Section titled “GlassContainer”](#glasscontainer) A Liquid Glass container that wraps Apple’s [`GlassEffectContainer`](https://developer.apple.com/documentation/swiftui/glasseffectcontainer) to provide a modern glassmorphism effect for grouping content. iOS 26 SDK Required This component uses Apple’s `GlassEffectContainer` API which requires **Xcode with iOS 26 SDK** to build. If you’re using an older Xcode version, you’ll encounter build errors: ```plaintext - value of type 'some View' has no member 'glassEffect' - cannot find 'GlassEffectContainer' in scope ``` **Workaround:** Avoid using this component until iOS 26 SDK is available in your Xcode version. At runtime, devices with iOS < 26 will gracefully fall back to a regular container without the glass effect. **Parameters:** * `spacing` (number, optional): Spacing between glass elements **Availability:** * **Build:** Requires Xcode with iOS 26 SDK (uses `GlassEffectContainer` API) * **Runtime:** iOS 26+ for glass effect, graceful fallback on earlier versions **Apple Documentation:** [GlassEffectContainer](https://developer.apple.com/documentation/swiftui/glasseffectcontainer) # Components Overview (iOS) > Overview of the SwiftUI primitives Voltra exposes for Live Activities and widgets, grouped into layout, visual, status, and interactive components. Voltra provides SwiftUI primitives with JSX bindings, allowing developers to create rich, interactive Live Activities using React/JSX syntax. ## Getting Started [Section titled “Getting Started”](#getting-started) Import iOS primitives from `@use-voltra/ios` and use the `Voltra` namespace: ```tsx import { Voltra } from '@use-voltra/ios' const MyComponent = () => { // Use any component return ( Hello Live Activity! Tap me ) } ``` ## Component Categories [Section titled “Component Categories”](#component-categories) Voltra organizes its components into categories: ### Layout & Containers [Section titled “Layout & Containers”](#layout--containers) Components that arrange other elements or provide structural grouping. These include stacks (VStack, HStack, ZStack), spacers, and container components like GroupBox and GlassContainer. [See all layout & container components →](/ios/components/layout) ### Visual Elements & Typography [Section titled “Visual Elements & Typography”](#visual-elements--typography) Static or decorative elements used to display content. This category includes Text, Label, Image, Symbol, and visual effects like LinearGradient, Mask, and Divider. [See all visual elements & typography components →](/ios/components/visual) ### Data Visualization & Status [Section titled “Data Visualization & Status”](#data-visualization--status) Components for displaying data and status information. This includes progress indicators (LinearProgressView, CircularProgressView), gauges, and timers for showing dynamic information in Live Activities. [See all data visualization & status components →](/ios/components/status) ### Interactive Controls & Navigation [Section titled “Interactive Controls & Navigation”](#interactive-controls--navigation) User interface controls that respond to user interaction and navigation. This category includes Button and Toggle components for interactive Live Activities, plus Link for semantic URL navigation. [See all interactive control & navigation components →](/ios/components/interactive) # Data Visualization & Status (iOS) > Reference for Voltra iOS components that show values and progress over time, including LinearProgressView and its timer-based mode. Components specifically designed to show dynamic values or states over time in Live Activities and Widgets. ### LinearProgressView [Section titled “LinearProgressView”](#linearprogressview) A horizontal progress bar that displays determinate progress or timer-based progress. #### Limitations [Section titled “Limitations”](#limitations) * When using `timerInterval` for smooth animations, custom styling properties such as `height`, `trackColor`, `cornerRadius`, and the `thumb` component are ignored. The component will use the default system appearance in this mode. *** ### CircularProgressView [Section titled “CircularProgressView”](#circularprogressview) A circular progress indicator that displays determinate progress or timer-based progress. #### Limitations [Section titled “Limitations”](#limitations-1) * While `timerInterval` is supported, the progress ring will not animate continuously. It only updates its visual state when the component state is refreshed. For a smooth, live-animating progress bar, use `LinearProgressView`. *** ### Gauge [Section titled “Gauge”](#gauge) A gauge indicator for progress visualization (iOS 16+). *** ### Timer [Section titled “Timer”](#timer) A flexible component for displaying live-updating time intervals. Crucial for Live Activities, it uses native SwiftUI text interpolation to ensure the time updates automatically on the lock screen and in the Dynamic Island without requiring background updates from React Native. **Modes:** * **Timer Mode:** For fixed intervals (countdowns or counting up to a target). Requires `endAtMs` or `durationMs`. * **Stopwatch Mode:** For open-ended intervals counting up from a starting point. Requires `startAtMs` and `direction="up"`, but both `endAtMs` and `durationMs` must be omitted. **Parameters:** * `startAtMs` (number, optional): Start time in milliseconds since epoch. * `endAtMs` (number, optional): End time in milliseconds since epoch. * `durationMs` (number, optional): Duration in milliseconds. Used if `endAtMs` is omitted. * `direction` (string, optional): Count direction. Can be `'up'` or `'down'`. Defaults to `'down'`. * `textStyle` (string, optional): Formatting style. * `'timer'`: Standard clock format (e.g., `05:00`). * `'relative'`: Relative format (e.g., `5m`). * `showHours` (boolean, optional): Whether to show hours (e.g., `1:30:00` vs `90:00`). Defaults to `false`. * `textTemplates` (string, optional): JSON-encoded object with `running` and `completed` templates. Use `{time}` as a placeholder. **Examples:** ```tsx // Timer Mode: Countdown 5 minutes // Stopwatch Mode: Count up indefinitely from now // Relative Timer with Template ``` # Visual Elements & Typography (iOS) > Reference for Voltra iOS visual components such as Text, Image, Symbol, and other elements that display static content. Static or decorative elements used to display content. ### Text [Section titled “Text”](#text) Displays text content. **Parameters:** * `numberOfLines` (number, optional): Maximum number of lines to display *** ### Label [Section titled “Label”](#label) A semantic label that can display both an icon and title text. **Parameters:** * `title` (string, optional): Text content for the label * `systemImage` (string, optional): SF Symbol name for the label icon *** ### Image [Section titled “Image”](#image) Displays bitmap images from the asset catalog or base64 encoded data. **Parameters:** * `source` (object, optional): Image source object (`assetName` or `base64`) * `resizeMode` (string, optional): `"cover"`, `"contain"`, `"stretch"`, `"repeat"`, or `"center"` * `fallback` (ReactNode, optional): Custom content rendered when the image is missing **Styling the fallback:** To add a background color when an image is missing, use `backgroundColor` in the `style` prop: ```jsx ``` *** ### Symbol [Section titled “Symbol”](#symbol) Displays SF Symbols (system icons) with configuration options. *** ### Divider [Section titled “Divider”](#divider) A visual divider component. *** ### LinearGradient [Section titled “LinearGradient”](#lineargradient) A linear gradient background that can contain children. *** ### Mask [Section titled “Mask”](#mask) Masks content using any Voltra element as the mask shape. # Configurable Widgets > Let users edit widget parameters in the iOS Edit Widget sheet by adding appIntent parameters to a Dynamic Widget. Configurable widgets let users edit widget parameters in the native iOS Edit Widget sheet. Use them when a Dynamic Widget needs a few user-editable knobs, such as a label, unit, theme, or source. It requires iOS 17+, because Voltra wires it through `AppIntentConfiguration`. ## How it works [Section titled “How it works”](#how-it-works) 1. Define a Dynamic Widget module with a default export. 2. Add `entry` and `appIntent.parameters` to the widget config in `app.json`. 3. Read the selected values from `env.configuration` in your widget’s JSX. 4. Build and install the app on a real iPhone, add the widget to the Home Screen, then long-press it and tap **Edit Widget** to change parameters — your widget re-reads `env.configuration` with the new values. Each parameter has: * `name`: key that appears in `env.configuration` * `title`: label shown in the Edit Widget sheet, as a plain string or a locale map * `default`: code-defined starting value before the user changes anything * `options` (optional): fixed values to pick from, each with a `value` and a `title`. The sheet shows a picker with the titles instead of a free-text field, and `env.configuration` receives the `value`. `default` must be one of the values; without a `default`, the first option is used. ## How to use it [Section titled “How to use it”](#how-to-use-it) ```tsx import { Voltra, type WidgetEnvironment } from '@use-voltra/ios' type GreetingConfig = { label?: string } export default function GreetingWidget( _props: object, env: WidgetEnvironment = {} as WidgetEnvironment ) { const label = env.configuration?.label ?? 'Hello' return ( {label} Edit me from the widget sheet. ) } ``` Plugin config: ```json { "expo": { "plugins": [ [ "@use-voltra/ios-client", { "widgets": [ { "id": "greeting_widget", "entry": "./widgets/ios/greeting-widget.tsx", "displayName": "Greeting Widget", "description": "A Dynamic Widget with user-editable parameters", "supportedFamilies": ["systemSmall", "systemMedium"], "initialStatePath": "./widgets/ios/greeting-widget.tsx", "appIntent": { "parameters": [ { "name": "label", "title": "Label", "default": "Hello" } ] } } ] } ] ] } } ``` If you need more than one value, add more entries to `appIntent.parameters` and read each key from `env.configuration`. ## Offer fixed choices [Section titled “Offer fixed choices”](#offer-fixed-choices) When a parameter has a known set of values, list them as `options`. The sheet then shows a picker: ```json { "name": "units", "title": "Units", "default": "metric", "options": [ { "value": "metric", "title": "Metric" }, { "value": "imperial", "title": "Imperial" } ] } ``` `env.configuration.units` is `"metric"` or `"imperial"`, whichever the user picked. Expo Prebuild and Voltra Apply stop with an error that names the parameter if `default` is not one of the values, a value is empty or listed twice, or an option has no `title`. ## Translate the Edit Widget sheet [Section titled “Translate the Edit Widget sheet”](#translate-the-edit-widget-sheet) iOS draws the Edit Widget sheet itself, so its text comes from `app.json` rather than from your widget code. `title` and `options[].title` accept locale maps, the same way `displayName` does. The sheet header shows the widget’s `displayName`, so translate it the same way: ```json { "id": "weather_widget", "entry": "./widgets/ios/weather-widget.tsx", "displayName": { "en": "Weather", "pl": "Pogoda" }, "description": { "en": "Current conditions", "pl": "Aktualne warunki" }, "appIntent": { "parameters": [ { "name": "units", "title": { "en": "Units", "pl": "Jednostki" }, "default": "metric", "options": [ { "value": "metric", "title": { "en": "Metric", "pl": "Metryczne" } }, { "value": "imperial", "title": { "en": "Imperial", "pl": "Imperialne" } } ] } ] } } ``` iOS shows the sheet in the system language, and `setDynamicWidgetLocale` does not affect it. A language with no translation for a string shows your app’s development language instead. Rebuild the native app after changing these. See [Localization](/ios/development/localization) for how the app’s languages are declared. ## Notes [Section titled “Notes”](#notes) * `appIntent` only wires up for Dynamic Widgets. * Defaults come from code, not from the native sheet. * There is no `export` field in app.json for Dynamic Widgets. * Use a real device to verify the Edit Widget flow. # Custom Fonts > Add custom fonts to iOS Live Activities and widgets through the plugin configuration or manually in Xcode, and use them with fontFamily. Voltra supports custom fonts through the `fontFamily` style property. ## Adding Custom Fonts to Your Project [Section titled “Adding Custom Fonts to Your Project”](#adding-custom-fonts-to-your-project) Voltra supports custom fonts in your Live Activities and Widgets through two main methods: ### 1. Using Voltra’s Font Configuration (Recommended) [Section titled “1. Using Voltra’s Font Configuration (Recommended)”](#1-using-voltras-font-configuration-recommended) The simplest way is to specify fonts directly in the Voltra plugin configuration. This follows the same pattern as `expo-font`: ```json { "expo": { "plugins": [ [ "@use-voltra/ios-client", { "groupIdentifier": "group.com.example.app", "fonts": ["./assets/fonts", "./assets/custom-font.ttf"] } ] ] } } ``` The `fonts` array can include: * Individual font files: `"./assets/fonts/CustomFont.ttf"` * Entire directories: `"./assets/fonts"` (all fonts in the directory will be included) * Supported formats: `.ttf`, `.otf`, `.woff`, `.woff2` ### 2. Adding Fonts Manually in Xcode [Section titled “2. Adding Fonts Manually in Xcode”](#2-adding-fonts-manually-in-xcode) For non-Expo projects or if you prefer manual configuration, you can add fonts directly to your Xcode project: 1. Add your font files (`.otf` or `.ttf`) to your Xcode project 2. Ensure they’re included in the Live Activity target’s “Copy Bundle Resources” build phase 3. Add the font file names to your `Info.plist` under the `UIAppFonts` key for Live Activity target For detailed instructions, see Apple’s documentation on [Applying custom fonts to text](https://developer.apple.com/documentation/swiftui/applying-custom-fonts-to-text). ## Using Custom Fonts [Section titled “Using Custom Fonts”](#using-custom-fonts) Once your fonts are added to the project, you can use them with the `fontFamily` style property: ```tsx import { Voltra } from '@use-voltra/ios' const element = ( Text with Custom Font ) ``` Font Family Names The font family name you use in `fontFamily` should match the font’s PostScript name, not the file name. You can find the PostScript name: * In the Font Book app on macOS * Using online tools like [fontdrop.info](https://fontdrop.info) * In Xcode’s font picker For example, the font file `Inter-Bold.ttf` has the PostScript name `Inter-Bold`. ## Font Weight with Custom Fonts [Section titled “Font Weight with Custom Fonts”](#font-weight-with-custom-fonts) When using `fontFamily`, the `fontWeight` style property is ignored since you typically specify the exact font variant (e.g., `Inter-Bold`, `Inter-Regular`). If you need different weights, add multiple font files and specify the complete font name: ```tsx // Regular weight Regular Text // Bold weight Bold Text ``` ## Example with Google Fonts [Section titled “Example with Google Fonts”](#example-with-google-fonts) If you’re using Google Fonts via `@expo-google-fonts`, they work seamlessly with Voltra: ```json { "expo": { "plugins": [ [ "expo-font", { "fonts": ["node_modules/@expo-google-fonts/inter/Inter_400Regular.ttf"] } ] ] } } ``` ```tsx Text using Google Font ``` System Font Fallback If `fontFamily` is not specified or the font cannot be found, Voltra will fall back to the system font with the specified `fontWeight`. # Developing Live Activities > Define Lock Screen and Dynamic Island variants for a Live Activity and use the APIs for building and testing them during development. Voltra provides APIs that make building and testing Live Activities easier during development. For bundled, on-device definitions that receive generic props rather than a rendered UI payload, see [Dynamic Live Activities](/ios/development/dynamic-live-activities). ## Supported variants [Section titled “Supported variants”](#supported-variants) Live Activities in iOS can appear in different contexts, and Voltra supports defining UI variants for each of these contexts. For detailed information about Live Activity design guidelines, see the [Apple Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/live-activities). ### Lock Screen [Section titled “Lock Screen”](#lock-screen) The `lockScreen` variant defines how your Live Activity appears on the lock screen. It can be either a ReactNode directly, or an object with content and optional styling: ```typescript const variants = { lockScreen: ( Your content here ), } ``` To customize the system Lock Screen chrome, pass an object with `content` and `activityBackgroundTint`: ```typescript const variants = { lockScreen: { activityBackgroundTint: '#101828', content: ( Your content here ), }, } ``` `activityBackgroundTint` is applied via SwiftUI’s `activityBackgroundTint(...)` modifier on iOS. Voltra currently accepts the same color formats handled by the native iOS parser: * Hex colors such as `#RGB`, `#RGBA`, `#RRGGBB`, and `#RRGGBBAA` * `rgb(...)` and `rgba(...)` * `hsl(...)` and `hsla(...)` * Named colors: `red`, `orange`, `yellow`, `green`, `mint`, `teal`, `cyan`, `blue`, `indigo`, `purple`, `pink`, `brown`, `white`, `gray`, `black`, `clear`, `transparent`, `primary`, `secondary` Use `clear` or `transparent` to make the Live Activity background transparent. If the string cannot be parsed as one of those formats, iOS ignores the tint. The tint changes the Lock Screen and banner background. It does not change the background of the Live Activity in CarPlay; see [Background color in CarPlay](#background-color-in-carplay). ### Dynamic Island [Section titled “Dynamic Island”](#dynamic-island) The `island` variant defines how your Live Activity appears in the Dynamic Island (available on iPhone 14 Pro and later). The Dynamic Island has three display states: * **Minimal**: A compact pill-shaped view that appears when the activity is in the background * **Compact**: A slightly larger view with leading and trailing regions * **Expanded**: A full-width view with center, leading, trailing, and bottom regions ```typescript const variants = { island: { keylineTint: '#10B981', // Optional tint color for the Dynamic Island keyline minimal: , compact: { leading: Order, trailing: Confirmed, }, expanded: { center: Order Confirmed, leading: , trailing: ETA: 15 min, bottom: Your order is being prepared, }, }, } ``` `keylineTint` uses the same iOS color parser and accepted formats as `activityBackgroundTint`. ### Supplemental Activity Families (iOS 18+, watchOS 11+) [Section titled “Supplemental Activity Families (iOS 18+, watchOS 11+)”](#supplemental-activity-families-ios-18-watchos-11) The `supplementalActivityFamilies` variant defines how your Live Activity appears on Apple Watch Smart Stack and CarPlay displays. This variant is optional and works seamlessly with your existing lock screen and Dynamic Island variants. ```typescript const variants = { lockScreen: ( {/* iPhone lock screen content */} ), island: { /* Dynamic Island variants for iPhone */ }, supplementalActivityFamilies: { small: ( 12 min ETA ), }, } ``` If `supplementalActivityFamilies.small` is not provided, Voltra will automatically construct it from your Dynamic Island `compact` variant by combining the leading and trailing content in an HStack. #### Background color in CarPlay [Section titled “Background color in CarPlay”](#background-color-in-carplay) In CarPlay, `activityBackgroundTint` has no effect. iOS draws the `small` layout on its own dark grey tile in both light and dark appearance, and `containerBackground` and `preferredColorScheme` don’t change it either. This is iOS behavior: Apple documents `activityBackgroundTint` as the background color of the Lock Screen presentation only. To use a different background in CarPlay, give the root of your `small` layout `flex: 1` and a `backgroundColor`. An opaque fill covers the whole tile: ```typescript supplementalActivityFamilies: { small: ( 12 min ), }, ``` Keep in mind: * Padding on the root without `flex: 1` leaves the grey tile visible around the content. * A translucent color blends with the grey tile and doesn’t replace it. * The same `small` layout is also used on Apple Watch Smart Stack, so check how a filled background looks there. * This was verified in Xcode 27’s CarPlay Simulator on an iPhone running iOS 27, not on a car head unit. ## Limitations [Section titled “Limitations”](#limitations) ### Animations and Live Updates [Section titled “Animations and Live Updates”](#animations-and-live-updates) There are specific constraints on how content can animate or update: * **Continuous Animations**: Custom continuous animations, such as rotating icons or elements moving along a path, are not supported. * **Smooth Updates**: Per-second “live” updates are only supported by specific components designed for this purpose: * `Timer`: For countdowns and stopwatches. * `LinearProgressView`: When used with `timerInterval`. * **Styling Trade-offs**: To enable smooth, system-driven animations (like a progress bar filling up in real-time), certain components may ignore custom styling properties (e.g., custom heights or thumb components) and fallback to standard system appearances. All other components only update their visual state when a new activity state is pushed from your application. ## useLiveActivity [Section titled “useLiveActivity”](#useliveactivity) For React development, Voltra provides the `useLiveActivity` hook for integration with the component lifecycle and automatic updates during development. Caution Unfortunately, iOS suspends background apps after approximately 30 seconds. This means that if you navigate away from your app (for example, to check the Dynamic Island or lock screen), live reload and auto-update functionality will be paused. ```typescript import { Voltra } from '@use-voltra/ios' import { useLiveActivity } from '@use-voltra/ios-client' function OrderLiveActivity({ orderId, status }) { const variants = { lockScreen: ( {status === 'confirmed' ? 'Order Confirmed' : 'Order Ready'} {status === 'confirmed' ? 'Your order is being prepared' : 'Your order is ready for pickup'} {status === 'ready' && ( I'm Here )} ), } const { start, update, end, isActive } = useLiveActivity(variants, { activityName: `order-${orderId}`, autoStart: true, // Automatically start when component mounts autoUpdate: true, // Automatically update when variants change deepLinkUrl: `myapp://order/${orderId}`, }) // Manual control if needed const handleCancelOrder = async () => { await end() } return ( Live Activity: {isActive ? 'Active' : 'Inactive'}