---
id: I0039
title: "Android network status widget"
url: https://carbium.sh/library/integrate/android-network-status-widget
collection: Integrations
category: Mobile and desktop
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Android network status widget

A small Node service reads slot, block height, epoch progress, recent transaction rate and node health from Carbium, caches the answer for 10 seconds, and serves one JSON document an Android home-screen widget fetches. The Carbium key stays on the server.

## What the widget shows

The widget is a small tile on an Android home screen that answers one question at a glance: is Solana mainnet up, and how busy is it. It does not talk to Carbium itself. A Node service you run does, and the widget fetches one JSON document from that service.

The service answers `GET /status` with an object that has these fields.

| Field | Read from | Meaning |
|---|---|---|
| ok | `getHealth` | true when the node answered ok, false when the call failed |
| slot | `getSlot` | newest slot at confirmed |
| blockHeight | `getBlockHeight` | block height at confirmed |
| epoch, epochPct | `getEpochInfo` | epoch number and the share of its slots already passed, one decimal |
| tps | `getRecentPerformanceSamples` | transactions per second over the newest sample window, one decimal |
| failed | none | names of the calls that failed in this refresh |
| at | none | UTC time of the refresh, as an ISO string |

Each of the five reads settles on its own. A failed one leaves its field `null` and puts its name in `failed`, so the tile can grey out one row and keep the rest. The server logs each failed name with the message of its error, which carries the HTTP status code when Carbium refused the call.

## The Solana side: five reads at one commitment

Carbium's [RPC endpoint](https://carbium.sh/docs#endpoints) is `https://services.carbium.sh`, and the service [sends the key](https://carbium.sh/docs#auth) in the `x-api-key` header. The key lives in an environment variable on your server. The phone never sees it, so a decompiled app gives away nothing.

Every read that takes a commitment asks for `confirmed`. `getHealth` and `getRecentPerformanceSamples` take no commitment.

A slot lasts about 200 ms, so the slot number on a tile that refreshes every few minutes is a sample of a fast-moving value. The widget should present it as a reading with an age. The `at` field exists for that: the app subtracts it from the phone's clock and writes `4 min ago` under the numbers.

`getRecentPerformanceSamples` returns windows of `samplePeriodSecs` seconds, each with a transaction count. The service asks for the newest one and divides the count by the period the node reports, which gives transactions per second over that window. Mainnet blocks carry no vote transactions, so the count is user and program activity. `getHealth` answers `ok` or fails, and the service turns that into the `ok` boolean.

## The status service

Install the one dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. `CARBIUM_KEY` is required and the file exits with a message when it is missing. `CARBIUM_RPC_URL` is optional. `PORT` decides the mode: with it set the file serves `GET /status`, and without it the file prints one status and exits, which is the quickest way to see the numbers.

`main.ts` (run: `node main.ts`)

```ts
// I0039 · Android network status widget
// https://carbium.sh/library/integrate/android-network-status-widget
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";
import { createServer } from "node:http";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);
const TTL_MS = 10_000; // one refresh per 10 s, however many phones ask
const commitment = "confirmed";
const send = <T>(call: { send(o: { abortSignal: AbortSignal }): Promise<T> }) =>
  call.send({ abortSignal: AbortSignal.timeout(5_000) });

async function read() {
  const names = ["getSlot", "getBlockHeight", "getEpochInfo", "getRecentPerformanceSamples", "getHealth"];
  const [slot, height, epoch, perf, health] = await Promise.allSettled([
    send(rpc.getSlot({ commitment })),
    send(rpc.getBlockHeight({ commitment })),
    send(rpc.getEpochInfo({ commitment })),
    send(rpc.getRecentPerformanceSamples(1)),
    send(rpc.getHealth()),
  ]);
  const failed: string[] = [];
  [slot, height, epoch, perf, health].forEach((r, i) => {
    if (r.status !== "rejected") return;
    failed.push(names[i]);
    // the error message carries the HTTP status (401, 429) and never the request headers
    console.error(`${names[i]} failed:`, r.reason instanceof Error ? r.reason.message : String(r.reason));
  });
  const e = epoch.status === "fulfilled" ? epoch.value : null;
  const p = perf.status === "fulfilled" ? perf.value[0] : undefined;
  return {
    ok: health.status === "fulfilled",
    slot: slot.status === "fulfilled" ? Number(slot.value) : null,
    blockHeight: height.status === "fulfilled" ? Number(height.value) : null,
    epoch: e ? Number(e.epoch) : null,
    epochPct: e ? Math.round((1000 * Number(e.slotIndex)) / Number(e.slotsInEpoch)) / 10 : null,
    tps: p ? Math.round((10 * Number(p.numTransactions)) / Number(p.samplePeriodSecs)) / 10 : null,
    failed,
    at: new Date().toISOString(),
  };
}

let cache = { body: "", at: 0 };
let inflight: Promise<void> | undefined;
async function current(): Promise<string> {
  if (Date.now() - cache.at > TTL_MS) {
    // the first request starts the refresh, the rest wait for the same promise
    inflight ??= read()
      .then((s) => {
        cache = { body: JSON.stringify(s), at: Date.now() };
      })
      .finally(() => {
        inflight = undefined;
      });
    await inflight;
  }
  return cache.body;
}

const port = process.env.PORT;
if (!port) {
  console.log(await current()); // no PORT: print one status and exit
} else {
  createServer(async (req, res) => {
    if (req.url !== "/status") return void res.writeHead(404).end();
    res.writeHead(200, { "content-type": "application/json" }).end(await current());
  }).listen(Number(port), () => console.log(`GET /status on :${port}`));
}
```

The cache is one string and a timestamp. When a request arrives after the 10 seconds are up, the first one starts a refresh and the others wait for that same promise, so a hundred phones waking together cause five calls in total.

## The Android side

Put the Node service behind HTTPS on a host you control. Apps that target Android 9 or later block plain HTTP by default, and a status endpoint on the public internet should be encrypted anyway. Nothing on it is secret, and the cache already holds Carbium calls to 0.5 a second, so a reverse proxy with a rate limit in front protects the Node host itself.

The widget itself is ordinary Android work, and any of the usual ways to build one fits.

- Build the tile with Jetpack Glance or with `RemoteViews`; the layout is a few text rows and a status dot driven by `ok`.
- Refresh from a periodic WorkManager job. WorkManager's minimum period is 15 minutes, and the widget's own `updatePeriodMillis` is rounded up to 30 minutes, so pick the job.
- In the job, call `GET /status` with a short timeout, parse the JSON, store it in the widget's state and ask the widget to redraw.
- On a failed fetch keep the old numbers and show their age. Do not replace them with zeros.
- Add a tap handler that enqueues one extra job, so the user can force a refresh. The server's cache still caps what that costs you.

Parse `slot` and `blockHeight` as 64-bit integers. Both are far below the limit where JSON numbers lose precision, so a plain number in the JSON is safe on both sides.

## What it costs against your limits

A refresh is five calls, and the cache allows one refresh every 10 seconds, so the service sends at most 0.5 calls a second to Carbium however many phones ask. Of those, `getSlot` and `getHealth` are [cached reads](https://carbium.sh/docs#rpc) at 1 cell each, and Free allows 5 req/s for that class. At the cache's pace they use 0.2 req/s.

[Limits are per account](https://carbium.sh/docs#limits), so every key on the account shares one budget. A call refused with a 429 lands in `failed`, and the next refresh after the cache expires tries again. The service does not retry inside a refresh.

A server that sits idle sends nothing. The cache refreshes only when a request arrives, so a widget on one phone that refreshes every 15 minutes costs five calls every 15 minutes.

## Where it ends

- The widget polls. It does not tick live, and Android decides when a background job actually runs, so a phone in battery saver can show numbers that are an hour old. Show their age.
- It reads one node's view through Carbium. It says nothing about whether your own transactions land.
- The tps figure is one sample window, usually about a minute. It moves with that window and says nothing about the next second.
- The service holds no history. A chart of the last day needs a store behind it, and the cache here is a single value.
- The Kotlin or Java side is yours. The service hands over JSON, and the layout, the job and the tap handler stay in your app.
- There is no alerting. A tile that turns red helps when someone looks at the phone; a page for an outage belongs to a separate watcher.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The widget stays on its loading state and Android logs a cleartext traffic error. | The URL starts with `http://`. Serve the service over HTTPS and point the app at that URL. An emulator reaches the host machine at `10.0.2.2`, but the HTTPS rule applies there too. |
| Every status comes back with `ok` false and all five names in `failed`, and the service log shows an HTTP error with status 401. | Carbium does not know the key. Check that `CARBIUM_KEY` holds the whole key with no quotes or trailing newline, and that nothing else sets `CARBIUM_RPC_URL` to a different host. |
| `failed` names some calls on and off, and the log shows HTTP 429. | The account's budget is spent, usually by other keys on it, since [limits are shared per account](https://carbium.sh/docs#limits). Lengthen `TTL_MS`, or lower the traffic elsewhere. |
| The service exits at once with `Set CARBIUM_KEY.` | The variable is missing in the environment the process starts in. Under systemd or a container, set it in the unit or the run command, not in your shell profile. |
| The tile shows the same numbers for hours while the service answers fine. | The refresh job is not running. Android defers background work on a sleeping phone. Show the age from `at` so the staleness is visible, and check that the app is not restricted in battery settings. |
| `tps` is `null` while the other fields fill in. | `getRecentPerformanceSamples` is in `failed`, or it returned an empty list. Run `node main.ts` without `PORT` to see the failed names and the status together. |

## Questions

### Why not call Carbium straight from the app?

A key inside an APK can be pulled out by anyone who downloads the app, and every install would spend your account's budget on its own. One server holds the key and one cache serves every phone.

### Can the widget use a WebSocket for live numbers?

A slot subscription costs 5 credits to open and then 20 credits per MiB sent, and a widget has no process that stays alive to hold the socket. Polling a cached status is the fit for a tile.

### How often can the widget refresh?

As often as WorkManager runs it, which is every 15 minutes at the shortest for a periodic job. A tap handler can start a one-off job between runs.

### What does this use on the Free plan?

Five calls per refresh and at most one refresh every 10 seconds, so at most 0.5 calls a second, of which the two cached reads are 0.2 req/s against a limit of 5.

## Related

- [Flutter account reads](https://carbium.sh/library/integrate/flutter-account-reads) (Integrations, I0004)
- [Solana commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels) (How to use Solana, HS0003)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
