> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mobilerun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Read app data as JSON

> Extract structured data from apps and serve it through an API.

Read Android settings as JSON, compare listings across apps, and expose a book lookup as an HTTP service.

> [accordion] Setup (once)
>
> ```bash Python theme={null}
> pip install mobilerun-sdk
> export MOBILERUN_API_KEY=dr_sk_...   # API Keys page
> export DEVICE_ID=...                 # a ready device from the dashboard
> python example.py
> ```
>
> ```bash TypeScript theme={null}
> npm init -y && npm pkg set type=module
> npm install @mobilerun/sdk && npm install -D tsx
> export MOBILERUN_API_KEY=dr_sk_...   # API Keys page
> export DEVICE_ID=...                 # a ready device from the dashboard
> npx tsx example.ts
> ```

## Read Settings as JSON

Read model, Android version and free storage from Settings as JSON with [typed output](https://docs.mobilerun.ai/sdk/helpers.md#typed-output).

**Needs:** [Cloud API key](https://docs.mobilerun.ai/api-keys.md) and credits · ready Cloud Android · Settings · no app account · `MOBILERUN_API_KEY` and `DEVICE_ID` · one-shot, a few minutes · device time and task credits; no residential traffic or add-ons.

> On my ready Android device, open Settings and read the device model, Android version and available free storage. Return the three values as JSON. Do not change settings or guess values.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import os
> from pydantic import BaseModel
> from mobilerun_sdk import MobilerunSDK
>
>
> class Settings(BaseModel):
>     model: str
>     android_version: str
>     free_storage: str
>
>
> mobilerun = MobilerunSDK()
> device = mobilerun.devices.from_id(os.environ["DEVICE_ID"])
> task = device.run(
>     task="Open Android Settings. Read the device model, Android version, and available free storage. "
>          "Copy each value as displayed; do not guess. Do not change any settings.",
>     output_schema=Settings,
> )
> print(f"Task: {task.id}", flush=True)
> print(task.wait_output().output.model_dump_json(indent=2))
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const mobilerun = new MobilerunSDK();
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
> const task = await device.run({
>   task: 'Open Android Settings. Read the device model, Android version, and available free storage. ' +
>     'Copy each value as displayed; do not guess. Do not change any settings.',
>   outputSchema: output(z.object({ model: z.string(), android_version: z.string(), free_storage: z.string() })),
> });
> console.log(`Task: ${task.id}`);
> console.log(JSON.stringify((await task.waitOutput()).output, null, 2));
> ```

![Settings showing Pixel 8 and 6.03 GB free](https://docs.mobilerun.ai/images/examples/extract-data/settings.png)

Result

```json theme={null}
{"model":"Pixel 8","android_version":"15","free_storage":"6.03 GB free"}
```

## Compare several apps

Compare Kindle Paperwhite listings from Amazon and eBay, or adapt the same pattern to LinkedIn and Indeed jobs.

**Needs:** cloud API key and credits · ready Cloud Android · Amazon and eBay · guest access, no third-party account · `MOBILERUN_API_KEY`, optional `DEVICE_ID`, `QUERY`, `MAX_RESULTS` · one-shot, several minutes · device time and task credits; no residential traffic or add-ons.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import json
> import os
> import sys
> from typing import Literal, Optional
> from pydantic import BaseModel
> from mobilerun_sdk import MobilerunSDK, WaitTimeoutError
>
> Condition = Literal["new", "used", "refurbished", "open_box", "unknown"]
>
>
> class Listing(BaseModel):
>     title: str
>     price_text: str
>     price: float
>     currency: str
>     condition_label: str
>     seller_or_shipping: Optional[str]
>     sponsored: bool
>
>
> class Listings(BaseModel):
>     offers: list[Listing]
>
>
> def normalize_condition(label: str) -> Condition:
>     mapping: dict[str, Condition] = {
>         "new": "new", "brand new": "new", "used": "used", "pre-owned": "used",
>         "like-new": "used", "open box": "open_box", "refurbished": "refurbished",
>         "good - refurbished": "refurbished", "excellent - refurbished": "refurbished",
>         "very good - refurbished": "refurbished", "certified - refurbished": "refurbished",
>     }
>     return mapping.get(label.strip().lower(), "unknown")
>
>
> # Add another store as a (name, Android package) pair.
> STORES = [("Amazon", "com.amazon.mShop.android.shopping"), ("eBay", "com.ebay.mobile")]
> query = os.environ.get("QUERY", "Kindle Paperwhite")
> max_results = int(os.environ.get("MAX_RESULTS", "3"))
> if max_results < 1:
>     raise ValueError("MAX_RESULTS must be positive")
> mobilerun = MobilerunSDK()
> device_id = os.getenv("DEVICE_ID")
> device = mobilerun.devices.from_id(device_id) if device_id else next(iter(mobilerun.devices.list(state=["ready"], platform="android")), None)
> if not device:
>     raise RuntimeError("No matching ready Android device found")
>
> offers = []
> failures = []
> for name, package in STORES:
>     try:
>         goal = (f"Open the {name} app ({package}). Continue as guest; dismiss sign-in prompts without signing in. "
>                 f"Search for {json.dumps(query)}. Collect up to {max_results} matching listings, scrolling as needed. "
>                 "Only include the searched product itself in the same model line, not other models, accessories, cases, or bundles with a different main item. Skip nonmatching listings, including sponsored listings. "
>                 "Copy price_text exactly as displayed and use its numeric amount as price, and ISO currency code. "
>                 "Copy condition_label exactly as displayed, such as Open Box or Pre-Owned; use an empty string if no explicit condition is displayed. Copy an explicit condition phrase even if it appears in the title; never infer a condition. Use null for unknown seller_or_shipping. "
>                 "Set sponsored true only when the listing is labeled sponsored. Omit listings with unclear title or price; never estimate. "
>                 "Never sign in, buy, or add to cart. Stop on the search results screen.")
>         task = device.run(task=goal, output_schema=Listings, max_steps=60, execution_timeout=300)
>         print(f"{name} task: {task.id}", file=sys.stderr, flush=True)
>         found = task.wait_output(timeout=360).output.offers[:max_results]
>         if not found:
>             raise ValueError("No offers returned")
>         offers.extend({"store": name, "condition": normalize_condition(o.condition_label), **o.model_dump()} for o in found)
>     except Exception as exc:
>         failures.append(name)
>         print(f"{name}: {exc}", file=sys.stderr)
>         if isinstance(exc, WaitTimeoutError):
>             print("Task may still be running; skipping remaining stores to avoid device conflicts.", file=sys.stderr)
>             break
>
> offers.sort(key=lambda offer: (offer["currency"], offer["price"]))
> with open("offers.json", "w", encoding="utf-8") as f:
>     json.dump(offers, f, indent=2, ensure_ascii=False)
> print(f"{'Store':<10} {'Price':<16} {'Condition':<12} {'Sponsored':<10} Title")
> for offer in offers:
>     print(f"{offer['store']:<10} {offer['price_text']:<16} {offer['condition']:<12} {str(offer['sponsored']):<10} {offer['title']}")
> for currency in sorted({offer["currency"] for offer in offers}):
>     cheapest = next(offer for offer in offers if offer["currency"] == currency)
>     print(f"Cheapest in {currency}: {cheapest['store']} {cheapest['title']} ({cheapest['price_text']})")
> if failures:
>     print(f"Incomplete comparison; failed stores: {', '.join(failures)}", file=sys.stderr)
> if not offers:
>     sys.exit(1)
> ```
>
> ```typescript TypeScript theme={null}
> import { writeFile } from 'node:fs/promises';
> import { MobilerunSDK, WaitTimeoutError } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> type Condition = 'new' | 'used' | 'refurbished' | 'open_box' | 'unknown';
> function normalizeCondition(label: string): Condition {
>   const mapping: Record<string, Condition> = {
>     'new': 'new', 'brand new': 'new', 'used': 'used', 'pre-owned': 'used',
>     'like-new': 'used', 'open box': 'open_box', 'refurbished': 'refurbished',
>     'good - refurbished': 'refurbished', 'excellent - refurbished': 'refurbished',
>     'very good - refurbished': 'refurbished', 'certified - refurbished': 'refurbished',
>   };
>   return mapping[label.trim().toLowerCase()] ?? 'unknown';
> }
> const listings = z.object({
>   offers: z.array(z.object({
>     title: z.string(), price_text: z.string(), price: z.number(), currency: z.string(),
>     condition_label: z.string(), seller_or_shipping: z.string().nullable(), sponsored: z.boolean(),
>   })),
> });
> // Add another store with its Android package.
> const stores = [
>   { name: 'Amazon', packageName: 'com.amazon.mShop.android.shopping' },
>   { name: 'eBay', packageName: 'com.ebay.mobile' },
> ];
> const query = process.env.QUERY ?? 'Kindle Paperwhite';
> const maxResults = Number(process.env.MAX_RESULTS ?? '3');
> if (!Number.isInteger(maxResults) || maxResults < 1) throw new Error('MAX_RESULTS must be a positive integer');
> const mobilerun = new MobilerunSDK();
> let device;
> if (process.env.DEVICE_ID) device = mobilerun.devices.fromId(process.env.DEVICE_ID);
> else for await (const ready of mobilerun.devices.list({ state: ['ready'], platform: 'android' })) { device = ready; break; }
> if (!device) throw new Error('No matching ready Android device found');
> const offers: (z.infer<typeof listings>['offers'][number] & { store: string; condition: Condition })[] = [];
> const failures: string[] = [];
> for (const store of stores) {
>   try {
>     const goal = `Open the ${store.name} app (${store.packageName}). Continue as guest; dismiss sign-in prompts without signing in. ` +
>       `Search for ${JSON.stringify(query)}. Collect up to ${maxResults} matching listings, scrolling as needed. ` +
>       'Only include the searched product itself in the same model line, not other models, accessories, cases, or bundles with a different main item. Skip nonmatching listings, including sponsored listings. ' +
>       'Copy price_text exactly as displayed and use its numeric amount as price, and ISO currency code. ' +
>       'Copy condition_label exactly as displayed, such as Open Box or Pre-Owned; use an empty string if no explicit condition is displayed. Copy an explicit condition phrase even if it appears in the title; never infer a condition. Use null for unknown seller_or_shipping. ' +
>       'Set sponsored true only when the listing is labeled sponsored. Omit listings with unclear title or price; never estimate. ' +
>       'Never sign in, buy, or add to cart. Stop on the search results screen.';
>     const task = await device.run({ task: goal, outputSchema: output(listings), maxSteps: 60, executionTimeout: 300 });
>     console.error(`${store.name} task: ${task.id}`);
>     const found = (await task.waitOutput({ timeoutMs: 360_000 })).output.offers.slice(0, maxResults);
>     if (!found.length) throw new Error('No offers returned');
>     offers.push(...found.map((o) => ({ store: store.name, condition: normalizeCondition(o.condition_label), ...o })));
>   } catch (error) {
>     failures.push(store.name);
>     console.error(`${store.name}: ${error}`);
>     if (error instanceof WaitTimeoutError) { console.error('Task may still be running; skipping remaining stores to avoid device conflicts.'); break; }
>   }
> }
> offers.sort((a, b) => a.currency.localeCompare(b.currency) || a.price - b.price);
> await writeFile('offers.json', JSON.stringify(offers, null, 2) + '\n');
> console.log(`${'Store'.padEnd(10)} ${'Price'.padEnd(16)} ${'Condition'.padEnd(12)} ${'Sponsored'.padEnd(10)} Title`);
> for (const offer of offers) console.log(`${offer.store.padEnd(10)} ${offer.price_text.padEnd(16)} ${offer.condition.padEnd(12)} ${String(offer.sponsored).padEnd(10)} ${offer.title}`);
> for (const currency of [...new Set(offers.map(o => o.currency))]) {
>   const cheapest = offers.find(o => o.currency === currency)!;
>   console.log(`Cheapest in ${currency}: ${cheapest.store} ${cheapest.title} (${cheapest.price_text})`);
> }
> if (failures.length) console.error(`Incomplete comparison; failed stores: ${failures.join(', ')}`);
> if (!offers.length) process.exitCode = 1;
> ```

![eBay listing for Kindle Paperwhite at \$54.99](https://docs.mobilerun.ai/images/examples/extract-data/ebay-live.png)

Result

```text theme={null}
Cheapest in USD: eBay Kindle Paperwhite 10th Generation 6" 8gb (Black) ($54.99)
```

## Serve it as an API

Start a local book-lookup server, then request `http://127.0.0.1:8000/books/a-light-in-the-attic_1000` until the result is ready.

**Needs:** cloud API key and credits · ready Cloud Android · Chrome and internet · no site account · `MOBILERUN_API_KEY` and `DEVICE_ID` · keeps running until Ctrl+C · device time and task credits per uncached lookup; no residential traffic or add-ons.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import json
> import logging
> import os
> import re
> import threading
> import time
> from datetime import datetime, timezone
> from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
> from typing import Optional
> from urllib.parse import urlparse
> from pydantic import BaseModel
> from mobilerun_sdk import MobilerunSDK, Task
>
> TTL, DEADLINE = 300, 600
> mobilerun = MobilerunSDK(max_retries=0)
> device = mobilerun.devices.from_id(os.environ.get("DEVICE_ID", ""))
> lock = threading.Lock()
> cache = {}
> job = None
> failure = None
>
>
> class Lookup(BaseModel):
>     found: bool
>     title: Optional[str] = None
>     price: Optional[str] = None
>     in_stock: Optional[bool] = None
>     stock_count: Optional[int] = None
>
>
> def to_book(out: Lookup, slug: str):
>     if not out.found:
>         return None
>     if (not out.title or not out.title.strip() or not out.price or not re.fullmatch(r"£[0-9]+\.[0-9]{2}", out.price)
>             or out.in_stock is None or out.stock_count is None or out.stock_count < 0
>             or out.in_stock != (out.stock_count > 0)):
>         raise ValueError("Invalid product fields")
>     return {"title": out.title, "price": out.price, "in_stock": out.in_stock, "stock_count": out.stock_count,
>             "url": f"https://books.toscrape.com/catalogue/{slug}/index.html"}
>
>
> def finish(slug: str, task: "Task[Lookup]"):
>     global job, failure
>     try:
>         book = to_book(task.wait_output(timeout=DEADLINE).output, slug)  # waits for the task to complete
>         if book is None:
>             with lock:
>                 failure = {"slug": slug, "task_id": task.id, "status": "not_found"}
>             return
>         fetched_at = datetime.now(timezone.utc).isoformat()
>         with lock:
>             cache[slug] = (time.monotonic() + TTL, book, fetched_at)
>     except Exception as exc:
>         logging.exception("Task failed")
>         with lock:
>             failure = {"slug": slug, "task_id": task.id, "status": str(exc)}
>     finally:
>         with lock:
>             job = None
>
>
> class Handler(BaseHTTPRequestHandler):
>     def send_json(self, code, data, retry=False):
>         body = json.dumps(data).encode("utf-8")
>         self.send_response(code)
>         self.send_header("Content-Type", "application/json; charset=utf-8")
>         self.send_header("Content-Length", str(len(body)))
>         if retry:
>             self.send_header("Retry-After", "15")
>         self.end_headers()
>         self.wfile.write(body)
>
>     def do_GET(self):
>         global job, failure
>         url = urlparse(self.path)
>         match = re.fullmatch(r"/books/([a-z0-9-]+_[0-9]+)", url.path)
>         if not match or url.query or url.fragment:
>             return self.send_json(400, {"error": "Use /books/<slug>, for example a-light-in-the-attic_1000"})
>         slug = match.group(1)
>         with lock:
>             entry = cache.get(slug)
>             if entry and entry[0] > time.monotonic():
>                 return self.send_json(200, {"book": entry[1], "cached": True, "fetched_at": entry[2]})
>             if job:
>                 if job["slug"] == slug:
>                     return self.send_json(202, {"status": "pending", "task_id": job["task_id"]}, True)
>                 return self.send_json(409, {"error": "device_busy", "running_slug": job["slug"]}, True)
>             if failure and failure["slug"] == slug:
>                 result, failure = failure, None
>                 return self.send_json(404 if result["status"] == "not_found" else 502, {"error": result["status"] if result["status"] == "not_found" else "task_failed", "task_id": result["task_id"], "status": result["status"]})
>             try:
>                 product_url = f"https://books.toscrape.com/catalogue/{slug}/index.html"
>                 task = device.run(
>                     task=(f"Open Chrome and go to {product_url}. If the page clearly says not found, report found false. "
>                           "Otherwise read this product page and report found true. Copy its complete title and displayed price "
>                           "exactly, including the £ symbol. Read availability and the exact stock count from the product information. "
>                           "Never infer or guess. If any value is unreadable, fail the task rather than inventing it."),
>                     max_steps=40, output_schema=Lookup, timeout=30)
>             except Exception:
>                 logging.exception("Task submission failed; inspect device before retrying")
>                 return self.send_json(502, {"error": "submission_failed", "status": "unknown"})
>             job = {"slug": slug, "task_id": task.id}
>             threading.Thread(target=finish, args=(slug, task), daemon=True).start()
>             return self.send_json(202, {"status": "pending", "task_id": task.id}, True)
>
>     def do_POST(self):
>         self.send_json(405, {"error": "Only GET is supported"})
>
>     def send_error(self, code, message=None, explain=None):
>         self.send_json(code, {"error": message or "Request error"})
>
>
> if __name__ == "__main__":
>     if not os.environ.get("MOBILERUN_API_KEY") or not os.environ.get("DEVICE_ID"):
>         raise SystemExit("Set MOBILERUN_API_KEY and DEVICE_ID")
>     ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever()
> ```
>
> ```typescript TypeScript theme={null}
> import { createServer, type ServerResponse } from 'node:http';
> import { MobilerunSDK, type Task } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> type Book = { title: string; price: string; in_stock: boolean; stock_count: number; url: string };
> type Job = { slug: string; task_id: string };
> const ttl = 300_000, deadlineMs = 600_000;
> if (!process.env.MOBILERUN_API_KEY || !process.env.DEVICE_ID) throw new Error('Set MOBILERUN_API_KEY and DEVICE_ID');
> const mobilerun = new MobilerunSDK({ maxRetries: 0 });
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID);
> const cache = new Map<string, { expires: number; book: Book; fetched_at: string }>();
> let job: Job | null = null;
> let failure: (Job & { status: string }) | null = null;
> let submitting: string | null = null;
> const lookup = z.object({
>   found: z.boolean(), title: z.string().optional(), price: z.string().optional(),
>   in_stock: z.boolean().optional(), stock_count: z.int().optional(),
> });
>
> function toBook(b: z.infer<typeof lookup>, slug: string): Book | null {
>   if (!b.found) return null;
>   if (!b.title?.trim() || !b.price || !/^£[0-9]+\.[0-9]{2}$/.test(b.price) || b.in_stock === undefined ||
>       b.stock_count === undefined || b.stock_count < 0 || b.in_stock !== (b.stock_count > 0)) throw new Error('Invalid product fields');
>   return { title: b.title, price: b.price, in_stock: b.in_stock, stock_count: b.stock_count,
>     url: `https://books.toscrape.com/catalogue/${slug}/index.html` };
> }
> const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
> async function finish(slug: string, task: Task<z.infer<typeof lookup>>): Promise<void> {
>   try {
>     const book = toBook((await task.waitOutput({ timeoutMs: deadlineMs })).output, slug); // waits for the task to complete
>     if (!book) { failure = { slug, task_id: task.id, status: 'not_found' }; return; }
>     cache.set(slug, { expires: performance.now() + ttl, book, fetched_at: new Date().toISOString() });
>   } catch (err) {
>     console.error('Task failed', err);
>     failure = { slug, task_id: task.id, status: err instanceof Error ? err.message : String(err) };
>   } finally {
>     job = null;
>   }
> }
> function send(res: ServerResponse, code: number, data: unknown, retry = false) {
>   res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', ...(retry ? { 'Retry-After': '15' } : {}) });
>   res.end(JSON.stringify(data));
> }
> createServer(async (req, res) => {
>   if (req.method !== 'GET') return send(res, 405, { error: 'Only GET is supported' });
>   const url = new URL(req.url ?? '/', 'http://localhost');
>   const match = /^\/books\/([a-z0-9-]+_[0-9]+)$/.exec(url.pathname);
>   if (!match || url.search || url.hash) return send(res, 400, { error: 'Use /books/<slug>, for example a-light-in-the-attic_1000' });
>   const slug = match[1];
>   const entry = cache.get(slug);
>   if (entry && entry.expires > performance.now()) return send(res, 200, { book: entry.book, cached: true, fetched_at: entry.fetched_at });
>   if (job) return job.slug === slug
>     ? send(res, 202, { status: 'pending', task_id: job.task_id }, true)
>     : send(res, 409, { error: 'device_busy', running_slug: job.slug }, true);
>   // During submission there is no task ID yet; avoid starting another device task.
>   if (submitting) {
>     if (submitting !== slug) return send(res, 409, { error: 'device_busy', running_slug: submitting }, true);
>     while (submitting === slug) await sleep(100);
>     if (job && (job as Job).slug === slug) return send(res, 202, { status: 'pending', task_id: (job as Job).task_id }, true);
>     return send(res, 502, { error: 'submission_failed', status: 'unknown' });
>   }
>   if (failure?.slug === slug) {
>     const result = failure; failure = null;
>     return send(res, result.status === 'not_found' ? 404 : 502, { error: result.status === 'not_found' ? 'not_found' : 'task_failed', task_id: result.task_id, status: result.status });
>   }
>   submitting = slug;
>   try {
>     const productUrl = `https://books.toscrape.com/catalogue/${slug}/index.html`;
>     const task = await device.run({ task: `Open Chrome and go to ${productUrl}. If the page clearly says not found, report found false. Otherwise read this product page and report found true. Copy its complete title and displayed price exactly, including the £ symbol. Read availability and the exact stock count from the product information. Never infer or guess. If any value is unreadable, fail the task rather than inventing it.`, maxSteps: 40, outputSchema: output(lookup) }, { timeout: 30_000, maxRetries: 0 });
>     job = { slug, task_id: task.id };
>     void finish(slug, task);
>     return send(res, 202, { status: 'pending', task_id: task.id }, true);
>   } catch (err) {
>     console.error('Task submission failed; inspect device before retrying', err);
>     return send(res, 502, { error: 'submission_failed', status: 'unknown' });
>   } finally {
>     submitting = null;
>   }
> }).listen(8000, '127.0.0.1', () => console.log('Listening on http://127.0.0.1:8000'));
> ```

![Book product page showing £51.77 and 22 in stock](https://docs.mobilerun.ai/images/examples/extract-data/product-lookup.png)

Result

```json theme={null}
{"title":"A Light in the Attic","price":"£51.77","in_stock":true,"stock_count":22}
```

> [!NOTE]
>
> Verify extracted values before relying on them. The local API has no authentication; add access controls before exposing it.

## Run it on many devices

> [!TIP]
>
> This runs on as many devices as you need: each device gets the same task in parallel.

Read the same Settings values from each device and print one result per device.

**Needs:** 2+ ready Cloud Android devices · `DEVICE_IDS` or all ready devices · `MOBILERUN_API_KEY` · one-shot · device time and task credits

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import asyncio
> import os
> import sys
> from pydantic import BaseModel
> from mobilerun_sdk import AsyncMobilerunSDK, AsyncDevice
>
>
> class Settings(BaseModel):
>     model: str
>     android_version: str
>     free_storage: str
>
>
> mobilerun = AsyncMobilerunSDK()
> goal = ("Open Android Settings. Read the device model, Android version, and available free storage. "
>         "Copy each value as displayed; do not guess. Do not change any settings.")
>
>
> async def run(device: AsyncDevice) -> tuple[str, str, bool]:
>     name = device.name or device.id
>     try:
>         if device.state != "ready" or (device.info and device.info.platform) != "android":
>             raise RuntimeError("Device must be ready and Android")
>         task = await device.run(task=goal, output_schema=Settings)
>         print(f"{name} task: {task.id}", file=sys.stderr, flush=True)
>         return name, (await task.wait_output()).output.model_dump_json(), False
>     except Exception as exc:
>         return name, f"ERROR: {exc}", True
>
>
> async def main() -> None:
>     ids = list(dict.fromkeys(x.strip() for x in os.getenv("DEVICE_IDS", "").split(",") if x.strip()))
>     if ids:
>         devices = [await mobilerun.devices.get(i) for i in ids]
>     else:
>         devices = [d async for d in mobilerun.devices.list(state=["ready"], platform="android")]
>     if len(devices) < 2:
>         raise SystemExit("Select at least two ready Android devices")
>     results = await asyncio.gather(*(run(d) for d in devices))
>     print("Device | Result")
>     for name, result, _ in results:
>         print(f"{name} | {result}")
>     if any(failed for _, _, failed in results):
>         sys.exit(1)
>
>
> asyncio.run(main())
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK, type Device } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const mobilerun = new MobilerunSDK();
> const devices: Device[] = [];
> const ids = [...new Set((process.env.DEVICE_IDS ?? '').split(',').map(x => x.trim()).filter(Boolean))];
> if (ids.length) {
>   for (const id of ids) devices.push(await mobilerun.devices.get(id));
> } else {
>   for await (const device of mobilerun.devices.list({ state: ['ready'], platform: 'android' })) devices.push(device);
> }
> if (devices.length < 2) throw new Error('Select at least two ready Android devices');
> const settings = z.object({ model: z.string(), android_version: z.string(), free_storage: z.string() });
> const goal = 'Open Android Settings. Read the device model, Android version, and available free storage. ' +
>   'Copy each value as displayed; do not guess. Do not change any settings.';
> const results = await Promise.allSettled(devices.map(async device => {
>   if (device.state !== 'ready' || device.info?.platform !== 'android') throw new Error('Device must be ready and Android');
>   const task = await device.run({ task: goal, outputSchema: output(settings) });
>   console.error(`${device.name || device.id} task: ${task.id}`);
>   return JSON.stringify((await task.waitOutput()).output);
> }));
> console.log('Device | Result');
> results.forEach((result, index) => console.log(`${devices[index].name || devices[index].id} | ${result.status === 'fulfilled'
>   ? result.value : `ERROR: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`}`));
> if (results.some(result => result.status === 'rejected')) process.exitCode = 1;
> ```

![Settings showing Pixel 8 and 7.53 GB free](https://docs.mobilerun.ai/images/examples/extract-data/settings-parallel.png)

Result

```text theme={null}
Phone | Result
Docs test E (personal) | {"model":"Pixel 8","android_version":"15","free_storage":"7.53 GB free"}
Docs test F (codes) | {"model":"Pixel 9","android_version":"15","free_storage":"7.54 GB"}
```

## Next steps

* Learn about [structured output](https://docs.mobilerun.ai/agent.md#structured-output) and [task monitoring](https://docs.mobilerun.ai/tasks.md).
* Explore [cloud devices](https://docs.mobilerun.ai/devices.md) and [webhooks](https://docs.mobilerun.ai/webhooks.md).

> [accordion] For AI agents
>
> Start with the first example on a ready device the user names. Uses `device.run`, `task.waitOutput()`, device UI state, and a local HTTP API. Ask before starting a server or exposing it; never buy anything or use real accounts. Report the result and any failed step.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.