Running many phones
Name phones, run them in parallel from Python, Node.js, C# or the shell, renew mobile IP addresses, and keep a shelf of phones connected for days.
One droidline serve drives as many phones as your PC and network carry. Each phone gets its own command queue: commands to one phone run in order, and different phones run at the same time.
Give every phone a name
Every phone has a random ID such as k7d2q9xa. Give it a name you can remember when you pair it, or rename it later:
droidline pair 482913 --name shelf-01
droidline rename k7d2q9xa shelf-02
droidline devices
Names may use letters, digits, dots, dashes and underscores. A label with the same name stuck on the phone itself saves a lot of guessing.
Run them in parallel
Ask the server which phones are online, then give each one its own thread, task or background job:
from concurrent.futures import ThreadPoolExecutor
from droidline import Droidline
dl = Droidline()
def morning(name: str) -> str:
d = dl.device(name)
d.wake()
d.launch("com.example.app")
d.touch("text", "Check in", timeout=20)
return d.get_text("id", "status")
names = [p["name"] for p in dl.devices() if p["online"]]
with ThreadPoolExecutor(len(names) or 1) as pool:
for name, status in zip(names, pool.map(morning, names)):
print(name, status)import { Droidline } from "droidline";
const dl = new Droidline();
const phones = (await dl.devices()).filter((p) => p.online);
const results = await Promise.allSettled(phones.map(async (p) => {
const d = dl.device(p.name);
await d.wake();
await d.launch("com.example.app");
await d.touch("text", "Check in", { timeout: 20 });
return d.getText("id", "status");
}));
results.forEach((r, i) => console.log(phones[i].name, r.status === "fulfilled" ? r.value : r.reason.message));using Droidline;
using var client = new DroidlineClient();
var phones = (await client.DevicesAsync()).Where(p => p.Get<bool>("online")).ToList();
var results = await Task.WhenAll(phones.Select(async p =>
{
try
{
var d = client.Device(p.Get<string>("name"));
await d.WakeAsync();
await d.LaunchAsync("com.example.app");
await d.TouchAsync("text", "Check in", timeout: 20);
return await d.GetTextAsync("id", "status");
}
catch (DroidlineException e)
{
return e.Message;
}
}));
for (var i = 0; i < phones.Count; i++)
Console.WriteLine($"{phones[i].Get<string>("name")} {results[i]}");for name in $(droidline --json devices | jq -r '.value[] | select(.online) | .name'); do
(
droidline -d "$name" wake
droidline -d "$name" launch com.example.app
droidline -d "$name" touch text "Check in" --timeout 20
echo "$name: $(droidline -d "$name" get_text id status)"
) &
done
waitOne phone failing does not stop the others: in Python the exception comes out of pool.map when you reach that phone's result, in Node.js allSettled records it, in C# the catch inside each task returns its message, and in the shell each phone runs in its own subshell.
Share phones between scripts
This is optional. When several scripts or people use the same shelf, two of them can pick the same phone: their commands interleave, and both fail on screens they did not expect. A lease prevents that. A script borrows a free phone, uses it, and gives it back. While it holds the lease, requests to that phone without the lease fail with DEVICE_LEASED. Phones nobody leased behave as they always have.
from droidline import lease
with lease(wait=60) as d: # any free phone, waiting up to 60 s for one
d.launch("com.example.shop")
# given back here, even if the block raised
with lease("shelf-03") as d: ... # this phone
with lease(min_sdk=33, model="Pixel") as d: ...import { lease } from "droidline";
const d = await lease({ wait: 60 });
try {
await d.launch("com.example.shop");
} finally {
await d.release();
d.close();
}using Droidline;
await using (var d = await DroidlineClient.LeaseAsync(wait: 60)) // any free phone, waiting up to 60 s for one
{
await d.LaunchAsync("com.example.shop");
}
// given back here, even if the block threw
await using var shelf = await DroidlineClient.LeaseAsync("shelf-03"); // this phone
await using var pixel = await DroidlineClient.LeaseAsync(minSdk: 33, model: "Pixel");droidline lease --wait 60
# {"device":"a1b2c3d4","lease":"l-3f9a1c0d2e4b","name":"shelf-03","ttl":300}
droidline --lease l-3f9a1c0d2e4b touch text "Log in"
droidline release l-3f9a1c0d2e4b- No matching phone free within
wait(30 seconds by default):NO_FREE_DEVICE. - The lease ends with
release, or afterttlseconds without a command (300 by default). A long command keeps it alive while it runs. droidline devicesshows a leased phone asonline,leased.- A script that crashed while holding a phone: free it at once with
droidline release -d shelf-03. - The Appium bridge leases with the capability
droidline:lease, and the pytest plugin with--droidline-lease.
Give each phone its own network
With the per-app proxy, each phone can send one app through a different upstream. Save the upstreams once and assign them by name:
droidline proxy add kr1 socks5://user:pass@203.0.113.10:1080
droidline proxy add kr2 socks5://user:pass@203.0.113.11:1080
plan = {"shelf-01": "@kr1", "shelf-02": "@kr2"}
for name, upstream in plan.items():
dl.device(name).proxy(upstream, app="com.android.chrome")const plan = { "shelf-01": "@kr1", "shelf-02": "@kr2" };
for (const [name, upstream] of Object.entries(plan)) {
await dl.device(name).proxy(upstream, { app: "com.android.chrome" });
}var plan = new Dictionary<string, string> { ["shelf-01"] = "@kr1", ["shelf-02"] = "@kr2" };
foreach (var (name, upstream) in plan)
await client.Device(name).ProxyAsync(upstream, app: "com.android.chrome");droidline -d shelf-01 proxy @kr1 --app com.android.chrome
droidline -d shelf-02 proxy @kr2 --app com.android.chromeNew mobile IP addresses
On mobile data, switching airplane mode on and off usually gets a new address from the carrier. Open the airplane mode page with intent, then send both switches in one batch with cuts_network. The phone cannot receive commands while it is offline, so it finishes the batch on its own:
d.intent("android.settings.AIRPLANE_MODE_SETTINGS")
d.wait_idle()
switch = {"class": "android.widget.Switch", "visible": True} # the page's first switch
d.batch([("touch", switch), ("sleep", 3000), ("touch", switch)], cuts_network=True, wait=True)await d.intent("android.settings.AIRPLANE_MODE_SETTINGS");
await d.waitIdle();
const sw = { class: "android.widget.Switch", visible: true }; // the page's first switch
await d.batch([["touch", sw], ["sleep", 3000], ["touch", sw]], { cuts_network: true, wait: true });await d.IntentAsync("android.settings.AIRPLANE_MODE_SETTINGS");
await d.WaitIdleAsync();
var sw = new { @class = "android.widget.Switch", visible = true }; // the page's first switch
await d.BatchAsync(new object[] { ("touch", sw), ("sleep", 3000), ("touch", sw) }, cutsNetwork: true, wait: true);droidline -d shelf-01 intent android.settings.AIRPLANE_MODE_SETTINGS
droidline -d shelf-01 wait_idle
SWITCH='["touch",{"class":"android.widget.Switch","visible":true}]'
droidline -d shelf-01 batch "[$SWITCH,[\"sleep\",3000],$SWITCH]" --cuts_network --waitWithout wait the call returns {"accepted": true} at once and the result arrives later as a result event. Settings pages differ between phones, so check the switch on yours first; Recipes has the details and the other network switches.
Screens that turn off
Taps and swipes fail while a phone's screen is off. Call wake() before each job; it turns the screen on and dismisses a lock screen that has no PIN. For phones that run unattended, remove the PIN, pattern or password lock in the phone's settings, because Droidline cannot unlock it.
Staying connected for days
- Set battery optimization to Not restricted for Droidline, and allow it in any extra background limits your phone brand adds (Troubleshooting lists the usual places).
- The app starts by itself when the phone boots, once it is paired.
- After a reconnect the phone resends replies the PC missed, and repeated commands are not run twice. See Concepts.
droidline devicesshows each phone's route and missing permissions.last_seenindevices()tells you when an offline phone was last connected.- Keep the phones charging. A USB charger is enough; no data connection is needed.
Watching the shelf
Subscribe to device events to hear the moment a phone drops off or comes back:
from droidline import Droidline
dl = Droidline()
dl.subscribe(["device"])
dl.on("device", lambda e: print(e["name"], e["state"], e.get("route")))
input("Watching. Press Enter to stop.\n")import { Droidline } from "droidline";
import { createInterface } from "node:readline/promises";
const dl = new Droidline();
await dl.subscribe(["device"]);
dl.on("device", (e) => console.log(e.name, e.state, e.route ?? ""));
const rl = createInterface({ input: process.stdin, output: process.stdout });
await rl.question("Watching. Press Enter to stop.\n");
rl.close();
dl.close();using Droidline;
await using var client = new DroidlineClient();
await client.SubscribeAsync(new[] { "device" });
using var watch = client.On("device", e =>
Console.WriteLine($"{e.Get<string>("name")} {e.Get<string>("state")} {e.Get<string>("route")}"));
Console.WriteLine("Watching. Press Enter to stop.");
Console.ReadLine();droidline --json devices | jq -r '.value[] | "\(.name)\t\(if .online then "online" else "offline" end)\t\(.route)"'Updates
The app checks GitHub Releases once a day and shows a notification when a new version exists. Installing the update over the old app keeps the pairing.