Guías
Cloud Phones Explained and Hands-On ADB Batch Automation
Deploy Android cloud phones with Redroid and Docker, then use ADB, Python and uiautomator2 for batch checks, UI workflows and failure diagnostics.

Writing an Android automation script for a single device is usually straightforward. As the number of devices grows, problems begin to accumulate. Test devices are occupied, app versions differ, scripts disconnect midway, and failures leave no diagnostic evidence. Even a simple health check can become difficult to reproduce.
Cloud phones centralize Android runtime environments on servers, providing a foundation for continuous operation, consistent configuration, and batch scheduling. Making effective use of these capabilities requires understanding how Android runs, how the control connection is established, and how scripts determine whether a task has completed.
This article starts with the architecture, deploys Redroid with Docker, and then uses ADB and Python for single-device checks, concurrent checks across multiple devices, screenshot archiving, and diagnostic collection. It concludes by outlining the integration boundaries to preserve when connecting to a provider's OpenAPI.
The lab uses a Linux host, an Android 12 image, and Python 3.10 or later. Run the deployment scripts on the server. Automation scripts can run either on the server or locally through SSH forwarding. The login example requires your own test app and replacement control IDs. The provider API example defines an explicit data contract. A real integration requires adapting authentication and fields to the provider.
1 What Cloud Phones and Local Emulators Address
Consider Runtime Location and Processor Architecture Separately
A “cloud phone” describes where an Android runtime is deployed and delivered. Users access a remote instance from a computer, phone, or browser, while computation, app processes, and primary data remain on the server.
An “emulator” describes a category of technologies for implementing an Android runtime. Modern Android Emulator installations can use hardware virtualization acceleration. When the image architecture matches the host architecture, many instructions can execute directly on the host CPU.
You can break the selection process into three questions.
| Question | Common options | Main implications |
|---|---|---|
| Where does Android run? | Local computer, remote server | Resource ownership, remote access, and operations |
| How is Android isolated? | Virtual machine, container, remote physical device | Kernel boundaries, resource overhead, and failure scope |
| How are instruction sets matched? | ARM64, x86_64, with translation where needed | Native library compatibility and execution overhead |
For example, an ARM64 server can run an ARM64 Android environment, and an x86_64 server can also host cloud Android instances. Redroid supports both host architectures. For apps with native libraries, also check the ABIs included in the APK against the image's supported ABIs.
Evaluate performance using the target app, measuring startup time, time per task, peak memory usage, and success rates over extended runs. GPU rendering mode, video encoding, disk I/O, and host load all affect results. Report performance overhead and instance density together with the test conditions.
Continuous Operation Depends on Server-Side State
When a remote Android instance is running continuously, closing the local viewing window usually only disconnects the interactive session. The app remains subject to server resources, Android process management, network connectivity, and the provider's operating policies.
It is also important to distinguish the app process from the automation script. The app runs in the cloud, while a local Python script sends actions through ADB. If the local computer shuts down, subsequent script commands stop as well. Deploy tasks that need continuous execution to an execution node that stays online.
2 Understanding the Cloud Phone Pipeline Through a Single Click
A remote click passes through input transport, Android event handling, screen rendering, and video delivery. Automation also adds device connection, state verification, and result storage.
This pipeline involves four categories of capabilities.
Compute resources provide CPU, memory, and storage, along with GPU, rendering, and encoding resources configured as needed.
The Android runtime starts the system, isolates instances, and runs apps. Virtual machines typically have their own kernels, while containers share the host kernel. Resource density needs to be load-tested against the workload.
Remote interaction services forward input and return screen output. Encoding format, frame rate, resolution, network distance, and congestion collectively affect the interaction experience.
Management and scheduling services handle instance lifecycles, task assignment, health checks, and log and result archiving.
Video latency affects the experience of manual operation. Wait times in UI automation are primarily determined by page loading, device load, and the control connection, so assertions should be based on page state.
This lab uses Redroid for the Android runtime and scrcpy to view and control the screen. A browser-based console, tenant permissions, a WebRTC gateway, and a billing system require additional implementation.
3 Deploying Your First Redroid Instance on a Linux Server
Check the Host Requirements First
Redroid runs on the Linux host kernel. Prepare a Linux host where you can manage kernel modules and run privileged containers, and install Docker Engine. For learning, you can start with 4 CPU cores, 8 GB of RAM, and an SSD. Determine actual capacity through the load tests described later.
Redroid's kernel requirements include Binder, binderfs, ashmem or memfd, and the corresponding memory allocation capabilities. The official deployment instructions also list requirements such as a 4 KB page size. Check these in advance, particularly on ARM cloud servers. The Linux virtual machine behind Docker Desktop must meet the same requirements.
Run the following checks on the server.
uname -m
uname -r
getconf PAGE_SIZE
docker version
# Load the Binder driver. It may already be built into the kernel
sudo modprobe binder_linux devices="binder,hwbinder,vndbinder"
# Kernels that support binderfs will usually list binder here
grep -w binder /proc/filesystemsIf you see Module binder_linux not found, first check whether your distribution provides an additional modules package matching the running kernel. For Ubuntu kernels that provide this package, install it and then load the driver.
sudo apt-get update
sudo apt-get install -y "linux-modules-extra-$(uname -r)"
sudo modprobe binder_linux devices="binder,hwbinder,vndbinder"Package names and module configurations may differ for kernels customized by cloud providers. Follow the Redroid deployment instructions for the corresponding distribution. If the Binder driver, binderfs, or page size requirements are unmet, adjust the host environment first.
This example explicitly enables androidboot.use_memfd=true so that images supporting this option use memfd. With other images, verify the combination of the shared-memory implementation and the host kernel. The kernel version alone is insufficient to establish Android image compatibility.
Create the Container and Persist Its Data
Create a lab directory on the server, save the following as start-phone.sh, and run bash start-phone.sh. Android 12 is used here to match the examples that follow. App compatibility testing should use the Android versions your project actually supports.
#!/usr/bin/env bash
set -euo pipefail
PHONE_NAME="cloudphone-01"
PHONE_PORT="15555"
PHONE_IMAGE="redroid/redroid:12.0.0-latest"
PHONE_DATA_DIR="${PWD}/data/${PHONE_NAME}"
mkdir -p "$PHONE_DATA_DIR"
docker pull "$PHONE_IMAGE"
docker run -d \
--name "$PHONE_NAME" \
--restart unless-stopped \
--privileged \
--cpus="2" \
--memory="3g" \
-p "127.0.0.1:${PHONE_PORT}:5555" \
-v "${PHONE_DATA_DIR}:/data" \
"$PHONE_IMAGE" \
androidboot.use_memfd=true \
androidboot.redroid_width=720 \
androidboot.redroid_height=1280 \
androidboot.redroid_dpi=320 \
androidboot.redroid_gpu_mode=guest
docker ps --filter "name=${PHONE_NAME}"Several parameters deserve attention.
/datais mounted separately to a host directory, allowing app data to persist with that directory. Use a separate directory for each instance.127.0.0.1:15555:5555binds ADB to the server's loopback address. Remote access uses the SSH forwarding described below.guestenables software rendering, which is suitable for initially verifying connectivity and basic automation. For graphics performance, configure hardware acceleration according to your GPU, drivers, and image.--cpusand--memoryset the initial resource limits for this example. Adjust them based on monitoring if system startup or the target app struggles.--privilegedgives the container broad access to host devices and the kernel. Run the lab on a controlled host. A multi-tenant service also needs host isolation and access control.
After the first run, a container with this name already exists. Use the following commands for subsequent starts and restarts, respectively.
docker start cloudphone-01
docker restart cloudphone-01The 12.0.0-latest tag changes as maintenance updates are released. Once the environment is validated, record the image digest and use the same digest when reproducing the environment.
docker image inspect redroid/redroid:12.0.0-latest \
--format '{{json .RepoDigests}}'Connect Through ADB and Confirm Android Has Finished Booting
Install Android SDK Platform Tools on the machine that will run the automation, and ensure adb is on PATH. Ubuntu and Debian can also use their distribution packages.
sudo apt-get update
sudo apt-get install -y adb python3 python3-venv
python3 --version
adb version
adb start-server
adb connect 127.0.0.1:15555
adb devices -l
adb -s 127.0.0.1:15555 shell getprop sys.boot_completed
adb -s 127.0.0.1:15555 shell getprop ro.build.version.release
adb -s 127.0.0.1:15555 shell getprop ro.product.cpu.abilistConfirm that python3 --version reports version 3.10 or later. If the distribution's default Python is older, install a supported Python version and replace python3 in subsequent commands with the appropriate interpreter, such as python3.11.
A device entry in adb devices means the ADB transport is established. Continue checking sys.boot_completed and begin app automation after it returns 1. The first boot may take longer. The next section incorporates this waiting logic into a script.
By default, the ADB server uses port 5037 on the execution node. Here, 15555 is the device port mapped to Android's adbd. These ports serve connection management and device access, respectively.
Access the Server Instance from Your Local Computer
Keep ADB bound to the server's loopback address. Open a terminal locally, establish SSH forwarding, and leave that terminal running.
ssh -NT \
-o ExitOnForwardFailure=yes \
-o ServerAliveInterval=30 \
-L 127.0.0.1:15555:127.0.0.1:15555 \
your_user@your_serverRun the following in another local terminal.
adb connect 127.0.0.1:15555
scrcpy -s 127.0.0.1:15555Install scrcpy locally and ensure the device meets its video encoding requirements. To reduce transmission overhead, start by limiting screen size and frame rate.
scrcpy -s 127.0.0.1:15555 --max-size=1024 --max-fps=154 Organizing ADB Commands into a Reusable Python Module
The scripts that follow repeatedly handle connection, boot waiting, command timeouts, and screenshots. Centralizing these operations in a module allows business workflows to focus on whether the device currently meets the required conditions.
Create a directory on the automation execution node and save the following as adbkit.py. This module uses the Python standard library and accesses devices through the installed adb command.
from pathlib import Path
import shlex
import subprocess
import time
def run_adb(*args: str, serial: str | None = None,
timeout: float = 15) -> bytes:
command = ["adb"]
if serial is not None:
command.extend(["-s", serial])
command.extend(args)
try:
result = subprocess.run(
command,
capture_output=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
raise TimeoutError(f"ADB command exceeded {timeout:.1f} seconds") from exc
if result.returncode != 0:
message = (result.stderr or result.stdout).decode(
"utf-8", errors="replace"
).strip()
raise RuntimeError(message[:2000] or "ADB command failed")
return result.stdout
class Device:
def __init__(self, serial: str):
self.serial = serial
def shell(self, *args: str, timeout: float = 15) -> str:
# Android still invokes a shell, so quote each argument to preserve boundaries
output = run_adb(
"shell", shlex.join(args),
serial=self.serial, timeout=timeout,
)
return output.decode("utf-8", errors="replace").strip()
def wait_ready(self, timeout: float = 120) -> None:
deadline = time.monotonic() + timeout
last_error = "Android is booting"
def remaining() -> float:
seconds = deadline - time.monotonic()
if seconds <= 0:
raise TimeoutError("Device wait time exhausted")
return min(10, seconds)
while time.monotonic() < deadline:
try:
run_adb("connect", self.serial, timeout=remaining())
state = run_adb(
"get-state", serial=self.serial,
timeout=remaining(),
).decode().strip()
booted = self.shell(
"getprop", "sys.boot_completed",
timeout=remaining(),
)
if state == "device" and booted == "1":
return
last_error = f"state={state}, boot_completed={booted!r}"
except (RuntimeError, TimeoutError) as exc:
last_error = str(exc)
time.sleep(max(0, min(2, deadline - time.monotonic())))
raise TimeoutError(f"Boot wait timed out for {self.serial}, {last_error}")
def screenshot(self, destination: Path) -> None:
png = run_adb(
"exec-out", "screencap", "-p",
serial=self.serial, timeout=20,
)
if not png.startswith(b"\x89PNG\r\n\x1a\n"):
raise RuntimeError("Device returned an invalid PNG screenshot")
destination.write_bytes(png)This module preserves screenshot data as binary, sets a timeout for each command, and imposes an overall deadline on the boot wait. During connection, it rechecks device state. If it ultimately fails, the exception is passed to the caller for recording.
5 Validating a Single Device Before Scaling to Multiple Devices
Run the First Check with System Settings
The first health check uses the Android Settings app to reduce dependence on a test APK and accounts. The workflow waits for boot, confirms the package is installed, launches Settings, checks its process, and saves a screenshot.
Save the following as fleet.py in the same directory as adbkit.py.
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
import json
from pathlib import Path
import re
import time
from uuid import uuid4
from adbkit import Device, run_adb
def inspect_one(serial: str, output_dir: Path) -> dict:
started = time.monotonic()
output_dir.mkdir(parents=True, exist_ok=True)
device = Device(serial)
result = {
"serial": serial,
"ok": False,
"artifacts": str(output_dir),
}
try:
device.wait_ready(timeout=120)
package_path = device.shell("pm", "path", "com.android.settings")
if not package_path.startswith("package:"):
raise RuntimeError("Image is missing com.android.settings")
launch_output = device.shell(
"am", "start", "-W", "-a", "android.settings.SETTINGS",
timeout=30,
)
if "Error:" in launch_output:
raise RuntimeError(launch_output)
device.shell("pidof", "com.android.settings")
device.screenshot(output_dir / "screen.png")
result["ok"] = True
except Exception as exc:
result["error"] = f"{type(exc).__name__}: {exc}"
capture_errors = []
try:
device.screenshot(output_dir / "failure.png")
except Exception as capture_exc:
capture_errors.append(f"Screenshot collection failed, {capture_exc}")
try:
logs = device.shell(
"logcat", "-d", "-t", "200", timeout=15,
)
(output_dir / "logcat.txt").write_text(logs, encoding="utf-8")
except Exception as capture_exc:
capture_errors.append(f"Log collection failed, {capture_exc}")
result["capture_errors"] = capture_errors
result["elapsed_seconds"] = round(time.monotonic() - started, 2)
return result
def main() -> int:
parser = argparse.ArgumentParser(description="Concurrent Android device health checks")
parser.add_argument("--serials", nargs="+", required=True)
parser.add_argument("--workers", type=int, default=2)
args = parser.parse_args()
if args.workers < 1:
parser.error("--workers must be greater than 0")
# Deduplicate so each device receives only one task in this run
serials = list(dict.fromkeys(args.serials))
run_adb("start-server", timeout=20)
run_name = datetime.now().strftime("%Y%m%d_%H%M%S")
run_dir = Path("artifacts") / f"{run_name}_{uuid4().hex[:8]}"
run_dir.mkdir(parents=True)
results = []
with ThreadPoolExecutor(max_workers=min(args.workers, len(serials))) as pool:
futures = {}
for index, serial in enumerate(serials, start=1):
safe_name = re.sub(r"[^a-zA-Z0-9_.-]", "_", serial)[:80]
device_dir = run_dir / f"{index:03d}_{safe_name}"
future = pool.submit(inspect_one, serial, device_dir)
futures[future] = serial
for future in as_completed(futures):
serial = futures[future]
try:
result = future.result()
except Exception as exc:
result = {
"serial": serial,
"ok": False,
"error": f"{type(exc).__name__}: {exc}",
}
results.append(result)
# Save immediately after each device finishes to preserve completed results
with (run_dir / "results.jsonl").open("a", encoding="utf-8") as file:
file.write(json.dumps(result, ensure_ascii=False) + "\n")
print(json.dumps(result, ensure_ascii=False), flush=True)
results.sort(key=lambda item: item["serial"])
(run_dir / "summary.json").write_text(
json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8",
)
succeeded = sum(item["ok"] for item in results)
print(f"Checks complete, {succeeded}/{len(results)} succeeded, artifacts in {run_dir}")
return 0 if succeeded == len(results) else 1
if __name__ == "__main__":
raise SystemExit(main())Connect one device first to verify the complete execution pipeline.
python3 fleet.py --serials 127.0.0.1:15555 --workers 1Each run creates its own artifact directory. Successful devices save screen.png. For failed devices, the script makes a best-effort attempt to collect failure.png and logcat.txt. It appends one record to results.jsonl as each device finishes and writes the consolidated summary.json at the end of the run.
This step checks ADB, the Android system, app launch, and screenshot capture. Business acceptance testing also requires assertions for page state, API results, data writes, or other relevant outcomes.
Add Two Instances and Run Checks Concurrently
Run the following script in the same lab directory on the server. Each instance receives a separate port and data directory, using the same image as the first instance.
#!/usr/bin/env bash
set -euo pipefail
for index in 2 3; do
name="$(printf 'cloudphone-%02d' "$index")"
port="$((15554 + index))"
data_dir="${PWD}/data/${name}"
mkdir -p "$data_dir"
docker run -d \
--name "$name" \
--restart unless-stopped \
--privileged \
--cpus="2" \
--memory="3g" \
-p "127.0.0.1:${port}:5555" \
-v "${data_dir}:/data" \
redroid/redroid:12.0.0-latest \
androidboot.use_memfd=true \
androidboot.redroid_width=720 \
androidboot.redroid_height=1280 \
androidboot.redroid_dpi=320 \
androidboot.redroid_gpu_mode=guest
doneAll three instances retain the 3 GB per-instance memory limit. The host needs capacity for the actual Android workload, Docker, and the operating system. Reassess the 8 GB configuration suggested earlier for getting started with one instance.
If the script runs locally, end the original single-port SSH forwarding session and establish forwarding for all three ports.
ssh -NT \
-o ExitOnForwardFailure=yes \
-o ServerAliveInterval=30 \
-L 127.0.0.1:15555:127.0.0.1:15555 \
-L 127.0.0.1:15556:127.0.0.1:15556 \
-L 127.0.0.1:15557:127.0.0.1:15557 \
your_user@your_serverThen run the same health-check script.
python3 fleet.py \
--serials 127.0.0.1:15555 127.0.0.1:15556 127.0.0.1:15557 \
--workers 2The thread pool allows different devices to work concurrently. The example deduplicates device addresses within a run so that each device executes only one task. When expanding to multiple execution processes or nodes, add task leases or distributed locks keyed by device ID to prevent two tasks from operating the same interface simultaneously.
Start with a small measured concurrency level. Observe CPU, memory, I/O, task duration, and timeout rates before increasing the worker count. Random delays can help spread startup load. Page operations should still use explicit state checks to determine completion.
6 Writing UI-Level Business Workflows with uiautomator2
Inspect the Page Structure First
ADB is useful for installing apps, executing system commands, and retrieving logs. uiautomator2 adds UI element queries and interactions, allowing elements to be located by resource ID, text, and description.
Create a virtual environment in the automation directory and install the dependencies.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install 'uiautomator2>=3,<4' requests
python -m uiautomator2 versionKeep the device online and export the current page's UI hierarchy.
python - <<'PY'
from pathlib import Path
import uiautomator2 as u2
device = u2.connect("127.0.0.1:15555")
Path("hierarchy.xml").write_text(device.dump_hierarchy(), encoding="utf-8")
device.screenshot("current-screen.png")
print("Saved hierarchy.xml and current-screen.png")
PYPrefer a stable, unique resourceId, followed by description and text. Text-based selectors are affected by language and wording changes. Coordinate-based actions require additional handling for layout, scaling, and orientation changes. Accessibility trees may be incomplete for WebViews, games, and custom-drawn controls, so choose a targeting method suited to the app's implementation.
Write a Login Workflow with State Assertions
The following example assumes a test app with package name com.example.demo. Its login page provides the resource IDs username, password, and login, and its post-login page contains home_title. Install the test APK first and confirm the actual names in the UI hierarchy.
adb -s 127.0.0.1:15555 install -r ./demo.apkSave the following as login.py in the same directory as adbkit.py.
import argparse
from getpass import getpass
from pathlib import Path
from uuid import uuid4
import uiautomator2 as u2
from adbkit import Device
def login(serial: str, package: str, account: str, password: str) -> None:
Device(serial).wait_ready(timeout=120)
device = u2.connect(serial)
device.implicitly_wait(10)
artifact_dir = Path("artifacts") / f"login_{uuid4().hex}"
artifact_dir.mkdir(parents=True)
try:
device.app_start(package, stop=True)
username_field = device(resourceId=f"{package}:id/username")
password_field = device(resourceId=f"{package}:id/password")
login_button = device(resourceId=f"{package}:id/login")
if not username_field.wait(timeout=20):
raise TimeoutError("Login page loading timed out")
username_field.set_text(account)
password_field.set_text(password)
login_button.click()
home = device(resourceId=f"{package}:id/home_title")
if not home.wait(timeout=20):
raise TimeoutError("Expected home-page control did not appear after login submission")
print(f"[{serial}] Post-login page assertion passed")
except Exception:
# Handle diagnostic collection separately to preserve the original business exception
try:
device.screenshot(str(artifact_dir / "failure.png"))
except Exception as exc:
print(f"Failed to capture failure screenshot, {exc}")
try:
(artifact_dir / "hierarchy.xml").write_text(
device.dump_hierarchy(), encoding="utf-8",
)
except Exception as exc:
print(f"Failed to collect UI hierarchy, {exc}")
raise
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--serial", required=True)
parser.add_argument("--package", required=True)
args = parser.parse_args()
account = input("Test account ").strip()
password = getpass("Test password ")
login(args.serial, args.package, account, password)
if __name__ == "__main__":
main()Enter the test credentials when prompted.
python login.py --serial 127.0.0.1:15555 --package com.example.demoEach step has a defined purpose. Waiting for the login page handles cold startup. UI element selectors accommodate layout changes. The home-page control verifies the outcome, and saving the screen and UI hierarchy on exceptions supports reproduction. To verify the logged-in identity, also assert the user ID, account information, or a test API response.
If the app supports persistent login, first check whether the home page is already present before deciding whether to enter the login workflow. For steps with side effects, such as submitting orders, sending messages, or modifying accounts, confirm whether the server has already completed the operation before retrying.
Preserve Context When Handling Input and Dialogs
send_keys sends text to the currently focused input field. Click the target control before using it. The current uiautomator2 documentation states that it first tries the clipboard and attempts an auxiliary input method if that interface is unavailable. Validate the input path against the capabilities of your image.
# Place this snippet inside a business function with an already connected device
field = device(resourceId="com.example.demo:id/username")
field.click()
device.send_keys("Test account", clear=True)Handle permission dialogs according to the expected permission and specific button ID. First-launch onboarding, input method configuration, and runtime permissions can be handled during test environment initialization. When an unknown dialog appears during execution, preserving the current state and reporting an exception helps prevent unintended actions.
7 Keeping a Clear Device Model When Integrating a Provider's OpenAPI
For self-hosted instances, device addresses can be obtained from container configuration. With managed cloud phones, instance lists, runtime status, and ADB access information usually come from the provider's API.
Concentrate provider-specific differences in the integration layer. Business scripts receive only instance IDs and reachable ADB addresses, allowing continued reuse of Device and inspect_one.
The following defines an API contract for this tutorial. It uses a Bearer Token, page-number pagination, and the JSON response below. Real providers may use signed authentication, temporary credentials, cursor-based pagination, or dedicated connection proxies. Replace the corresponding implementation according to their official documentation.
{
"items": [
{
"id": "phone-001",
"status": "RUNNING",
"adb_endpoint": "127.0.0.1:15555"
}
],
"has_more": false
}Under this contract, the following code retrieves the instance list. Save it as cloud_api.py.
from dataclasses import dataclass
import os
import requests
@dataclass(frozen=True)
class CloudPhone:
instance_id: str
serial: str
class ExampleCloudClient:
def __init__(self, base_url: str, session: requests.Session):
if not base_url.startswith("https://"):
raise ValueError("OpenAPI URL must use HTTPS")
self.base_url = base_url.rstrip("/")
self.session = session
def list_running(self, max_pages: int = 100) -> list[CloudPhone]:
phones = {}
for page in range(1, max_pages + 1):
response = self.session.get(
f"{self.base_url}/v1/instances",
params={"page": page, "page_size": 50},
timeout=(5, 20),
)
response.raise_for_status()
payload = response.json()
items = payload["items"]
has_more = payload["has_more"]
if not isinstance(items, list) or not isinstance(has_more, bool):
raise ValueError("Invalid instance list response format")
for item in items:
if item["status"] == "RUNNING" and item.get("adb_endpoint"):
phone = CloudPhone(
instance_id=item["id"], serial=item["adb_endpoint"],
)
phones[phone.instance_id] = phone
if not has_more:
return list(phones.values())
raise RuntimeError("Pagination limit exceeded, check the API pagination contract")
if __name__ == "__main__":
# Supply these two environment variables from the actual provider configuration
with requests.Session() as session:
session.headers["Authorization"] = f"Bearer {os.environ['CLOUD_API_KEY']}"
client = ExampleCloudClient(os.environ["CLOUD_API_URL"], session)
phones = client.list_running()
print(f"Retrieved {len(phones)} running instances")Even after the list reports RUNNING, wait for Android to finish booting and confirm that the ADB access path is available. Some providers require obtaining temporary connection credentials or starting a local proxy first. The integration layer should complete these steps before returning serial.
Creating, restarting, and destroying instances also requires handling asynchronous task states. Break the operation into submitting the request, recording the task ID, polling status, confirming Android readiness, and handing over the device. If a creation request times out, first query its outcome using an idempotency key or request ID to avoid creating duplicate billable resources.
As the device count grows, the scheduling layer also needs to record task IDs, instance IDs, lease expiration times, and execution results. Workers continuously renew the lease after claiming a device and release it when the task ends, allowing instance lifecycles and business execution to be managed separately.
8 Troubleshooting Along the Pipeline
| Symptom | Check first | Actionable diagnostic steps |
|---|---|---|
| Container exits after starting | Kernel capabilities, image architecture, memory limits | Check docker logs cloudphone-01 and container state |
| ADB connection refused | Container status, port mappings, SSH forwarding | Run docker port cloudphone-01 5555/tcp |
| ADB is online but the app will not launch | Android boot status, installation result, package name | Check getprop sys.boot_completed and pm path |
| APK installation reports an ABI error | APK native libraries and system ABI | Run getprop ro.product.cpu.abilist |
| UI element is never found | Current page, resource ID, dialogs, custom-drawn components | Save a screenshot and dump_hierarchy() |
| Timeouts increase significantly under concurrency | Host load, memory reclamation, I/O, ADB latency | Check docker stats --no-stream and task durations |
Use the following commands together when investigating container state.
docker logs --tail 100 cloudphone-01
docker inspect cloudphone-01 --format '{{json .State}}'
docker port cloudphone-01 5555/tcp
docker stats --no-stream
adb -s 127.0.0.1:15555 shell getprop sys.boot_completed
adb -s 127.0.0.1:15555 shell pm path com.android.settings
adb -s 127.0.0.1:15555 logcat -d -t 200For remote display problems, continue checking rendering, encoding, and the network path. For UI workflow failures, prioritize page state and assertions. Investigating the pipeline layer by layer reduces the loss of diagnostic evidence caused by repeated restarts.
9 Choosing Between Self-Hosting and Managed Services
Self-hosting Redroid gives you control over images, data directories, and automation access, while requiring host maintenance, kernel compatibility management, capacity planning, and failure recovery. Managed cloud phones delegate these responsibilities to the provider, shifting evaluation toward APIs, service reliability, data management, and long-term costs.
Compare the following using the same set of test tasks.
App compatibility. Check Android versions, ABIs, graphics capabilities, required system services, and the target app's actual behavior.
Automation access. Confirm the ADB connection method, authentication, credential lifetimes, API rate limits, and asynchronous task query mechanisms.
Batch management. Check image distribution, batch APK installation, instance grouping, team permissions, and operation records.
Continuous operation. Measure task success rates, recovery time after restarts, and resource usage under the target workload.
Data management and cost. Check data isolation, backups, expiration handling, storage fees, traffic charges, and billing rules for stopped instances.
Final Thoughts
After completing the lab, you will have a persistent Android instance, a control connection accessible from an execution node, and a batch health-check script that generates screenshots and logs.
When scaling, first define the business assertions for the target app, then gradually add device leases, task queues, and failure recovery. Being able to verify every device's state and preserve evidence from every failure provides the foundation for reliable batch automation at scale.
Once you have deployed cloud phones and run scripts through ADB, the next consideration is how to integrate these capabilities into everyday business. Content publishing, customer communication, and multi-account collaboration all require devices, operating steps, and execution results to be organized into complete workflows. For teams looking to reduce low-level environment maintenance and begin mobile operations directly, Core-Mate offers a way to put these capabilities into practice. Core-Mate
Core-Mate is a mobile AI agent platform for social media operations teams that brings together task planning, app interaction, and managed Android cloud phones. Users describe their goals in natural language, and AI breaks them into steps and performs clicks, text entry, and page interactions within app interfaces. The platform builds workflows around social apps such as TikTok, Instagram, LinkedIn, and X, covering content publishing, creator outreach, and customer follow-up. The actions available depend on the app, account permissions, and supported skills. Core-Mate
Viewed through the technical pipeline introduced in this article, cloud phones provide an always-online runtime, while Core-Mate further coordinates goals, devices, and execution tasks. Teams can view plans, task status, and execution records in a unified workspace, review content before publishing or external communication, and adjust subsequent plans based on results. The platform maintains the managed cloud phones and also supports connecting your own Android devices. Core-Mate
Starting with a small, well-defined task, validating planning, review, execution, and result checks, and then gradually expanding to multi-device collaboration makes it easier to establish sustainable operations. To apply the automation approach described in this article to everyday work, explore the product and its workflows. Core-Mate
Thinking about AI, tasks, and connected devices.