Recipes
Ready-to-copy patterns for everyday tasks in Python, Node.js, C# and the shell, from starting an app fresh and dismissing pop-ups to reading lists, retrying, one-time codes and new IP addresses.
Each recipe solves one common task. Pick your language once and every example on the page follows. The examples assume a connected phone in d (d = connect() in Python, const d = await connect() in Node.js, await using var d = await DroidlineClient.ConnectAsync() in C#); in the shell, every droidline command finds the phone by itself.
Make sure the phone is ready
Wake the screen and check that it is not locked behind a PIN, which Droidline cannot unlock:
d.wake()
if d.locked():
raise SystemExit("Unlock the phone, or turn off its screen lock, first")
if d.battery()["level"] < 15:
print("Battery is low")await d.wake();
if (await d.locked()) throw new Error("Unlock the phone, or turn off its screen lock, first");
if ((await d.battery()).level < 15) console.log("Battery is low");await d.WakeAsync();
if (await d.LockedAsync())
throw new InvalidOperationException("Unlock the phone, or turn off its screen lock, first");
if ((await d.BatteryAsync()).Level < 15)
Console.WriteLine("Battery is low");droidline wake
if [ "$(droidline locked)" = "true" ]; then
echo "Unlock the phone first" >&2; exit 1
fiStart an app from a clean state
launch brings an app to the front where it left off. To start from its first screen, force stop it first. To start as if freshly installed, clear its data. Both happen in Android's Settings app, so they are recipes built from ordinary commands, shown further down:
force_stop(d, "com.example.shop") # from the recipe below
d.launch("com.example.shop")
clear_data(d, "com.example.shop") # wipes logins and settings too
d.launch("com.example.shop")await forceStop(d, "com.example.shop"); // from the recipe below
await d.launch("com.example.shop");
await clearData(d, "com.example.shop"); // wipes logins and settings too
await d.launch("com.example.shop");await ForceStopAsync(d, "com.example.shop"); // from the recipe below
await d.LaunchAsync("com.example.shop");
await ClearDataAsync(d, "com.example.shop"); // wipes logins and settings too
await d.LaunchAsync("com.example.shop");In device owner mode, clear_data(package) wipes the data directly, without opening Settings. droidline apps lists package names.
Dismiss pop-ups that may or may not appear
Ads, rating requests and tips come and go. Check for each with a condition, which never waits and never fails:
for text in ["Not now", "Close ad", "Skip", "Later"]:
if d.exists("text", text):
d.touch("text", text)for (const text of ["Not now", "Close ad", "Skip", "Later"]) {
if (await d.exists("text", text)) await d.touch("text", text);
}foreach (var text in new[] { "Not now", "Close ad", "Skip", "Later" })
{
if (await d.ExistsAsync("text", text))
await d.TouchAsync("text", text);
}for text in "Not now" "Close ad" "Skip" "Later"; do
if [ "$(droidline exists text "$text")" = "true" ]; then
droidline touch text "$text"
fi
doneIf a pop-up appears a moment after a screen opens, wait for whichever comes first with which, as in the next recipe.
Handle a step that can end in different places
After a tap, the app might show the next screen, an error, or a pop-up. which waits for the first of several candidates and tells you which one appeared:
d.touch("text", "Pay")
result = d.which([("text", "Payment complete"),
("textContains", "declined"),
("text", "Confirm")], timeout=30)
if result == 2:
d.touch("text", "Confirm")
elif result != 0:
d.screenshot("payment-problem.png")await d.touch("text", "Pay");
const result = await d.which([["text", "Payment complete"],
["textContains", "declined"],
["text", "Confirm"]], { timeout: 30 });
if (result === 2) await d.touch("text", "Confirm");
else if (result !== 0) await d.screenshot("payment-problem.png");await d.TouchAsync("text", "Pay");
var result = await d.WhichAsync(new object[]
{
("text", "Payment complete"),
("textContains", "declined"),
("text", "Confirm"),
}, timeout: 30);
if (result == 2)
await d.TouchAsync("text", "Confirm");
else if (result != 0)
await d.ScreenshotAsync("payment-problem.png");droidline touch text Pay
result=$(droidline which text="Payment complete" textContains=declined text=Confirm --timeout 30)
case "$result" in
2) droidline touch text Confirm ;;
0) ;;
*) droidline screenshot payment-problem.png ;;
esacWait for something to finish
Wait for a spinner or a "Loading" label to disappear, or for a result to appear:
d.wait_gone("id", "progress", 60)
d.wait("textContains", "Upload complete", 120)await d.waitGone("id", "progress", 60);
await d.wait("textContains", "Upload complete", 120);await d.WaitGoneAsync("id", "progress", 60);
await d.WaitAsync("textContains", "Upload complete", 120);droidline wait_gone id progress 60
droidline wait textContains "Upload complete" 120When there is nothing specific to wait for, such as a list that fills in or a page that slides in, wait until the screen stops changing instead of sleeping for a fixed time:
d.touch("text", "Search")
d.wait_idle() # nothing new drawn for 500 ms
d.wait_idle(1000, 20) # 1 s of quiet, give up after 20 sawait d.touch("text", "Search");
await d.waitIdle();
await d.waitIdle(1000, 20);await d.TouchAsync("text", "Search");
await d.WaitIdleAsync(); // nothing new drawn for 500 ms
await d.WaitIdleAsync(1000, 20); // 1 s of quiet, give up after 20 sdroidline touch text Search
droidline wait_idleA screen that animates all the time, such as a video or a spinner that never stops, ends in TIMEOUT; wait for a specific element there.
Type text and press keys
input fills a field, replacing what was there; append=True adds to it instead. sendkey presses a key, such as Enter to submit a search:
d.input("id", "search", "android automation")
d.sendkey("enter")
d.input("id", "note", " and more", append=True)
d.clear("id", "note")await d.input("id", "search", "android automation");
await d.sendkey("enter");
await d.input("id", "note", " and more", { append: true });
await d.clear("id", "note");await d.InputAsync("id", "search", "android automation");
await d.SendkeyAsync("enter");
await d.InputAsync("id", "note", " and more", append: true);
await d.ClearAsync("id", "note");droidline input id search "android automation"
droidline sendkey enterAny language and any script works, including Korean, Chinese and emoji. Key names include enter, tab, del, space, escape, back and home.
Read every item in a list
dump returns the whole tree, so you can collect values with a few lines of ordinary code:
def texts(node):
if node.get("text"):
yield node["text"]
for child in node.get("children", []):
yield from texts(child)
screen = d.dump()
print(list(texts(screen["tree"])))function* texts(node) {
if (node.text) yield node.text;
for (const child of node.children ?? []) yield* texts(child);
}
const screen = await d.dump();
console.log([...texts(screen.tree)]);static IEnumerable<string> Texts(Node node)
{
var text = node.Get<string>("text");
if (!string.IsNullOrEmpty(text))
yield return text;
foreach (var child in node.Get<List<Node>>("children") ?? new())
foreach (var t in Texts(child))
yield return t;
}
var screen = await d.DumpAsync();
Console.WriteLine(string.Join(", ", Texts(screen.Tree)));droidline dump | jq -r '.. | .text? // empty | select(. != "")'When the items share an id, find_all hands them to you directly, and each one can be searched inside:
for row in d.find_all("id", "item_row"):
print(row.find("id", "title").text, row.find("id", "price").text)for (const row of await d.findAll("id", "item_row")) {
console.log((await row.find("id", "title")).text, (await row.find("id", "price")).text);
}foreach (var row in await d.FindAllAsync("id", "item_row"))
{
var title = await row.FindAsync("id", "title");
var price = await row.FindAsync("id", "price");
Console.WriteLine($"{title.Text} {price.Text}");
}For a long list, collect, swipe up, collect again, and stop when nothing new appears:
seen = []
while True:
new = [t for t in texts(d.dump()["tree"]) if t not in seen]
if not new:
break
seen += new
d.swipe("up")
print(seen)const seen = [];
for (;;) {
const fresh = [...texts((await d.dump()).tree)].filter((t) => !seen.includes(t));
if (fresh.length === 0) break;
seen.push(...fresh);
await d.swipe("up");
}
console.log(seen);var seen = new List<string>();
while (true)
{
var fresh = Texts((await d.DumpAsync()).Tree).Where(t => !seen.Contains(t)).ToList();
if (fresh.Count == 0)
break;
seen.AddRange(fresh);
await d.SwipeAsync("up");
}
Console.WriteLine(string.Join(", ", seen));Keep a screenshot when something fails
Wrap a run so that any failure leaves a picture and a dump behind:
from datetime import datetime
from droidline import DroidlineError
try:
run_my_steps(d)
except DroidlineError:
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
d.screenshot(f"fail-{stamp}.png")
d.dump(f"fail-{stamp}.json")
raisetry {
await runMySteps(d);
} catch (e) {
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
await d.screenshot(`fail-${stamp}.png`);
await d.dump(`fail-${stamp}.json`);
throw e;
}try
{
await RunMyStepsAsync(d);
}
catch (DroidlineException)
{
var stamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
await d.ScreenshotAsync($"fail-{stamp}.png");
await d.DumpAsync($"fail-{stamp}.json");
throw;
}trap 'droidline screenshot "fail-$(date +%s).png"' ERRIn a test suite you do not need to write this yourself: the optional pytest plugin and Node.js helper, and Testing.SaveFailureAsync in .NET, save the screenshot, the screen tree and the phone's recent commands for each failed test.
Retry a step that sometimes fails
Errors say whether retrying might help. Retry only those:
import time
from droidline import DroidlineError
for attempt in range(3):
try:
d.touch("text", "Refresh")
break
except DroidlineError as e:
if not e.retryable or attempt == 2:
raise
time.sleep(2)import { DroidlineError } from "droidline";
for (let attempt = 0; ; attempt++) {
try {
await d.touch("text", "Refresh");
break;
} catch (e) {
if (!(e instanceof DroidlineError) || !e.retryable || attempt === 2) throw e;
await new Promise((r) => setTimeout(r, 2000));
}
}for (var attempt = 0; ; attempt++)
{
try
{
await d.TouchAsync("text", "Refresh");
break;
}
catch (DroidlineException e) when (e.Retryable && attempt < 2)
{
await Task.Delay(2000);
}
}for attempt in 1 2 3; do
droidline touch text Refresh && break
sleep 2
doneOpen a web page or a deep link
d.chrome.go("droidline.dev") # in Chrome, in the current tab
d.open_url("https://droidline.dev/docs/") # in the default browser
d.open_url("myapp://orders/42") # straight to a screen of an app that supports itawait d.chrome.go("droidline.dev");
await d.openUrl("https://droidline.dev/docs/");
await d.openUrl("myapp://orders/42");await d.Chrome.GoAsync("droidline.dev"); // in Chrome, in the current tab
await d.OpenUrlAsync("https://droidline.dev/docs/"); // in the default browser
await d.OpenUrlAsync("myapp://orders/42"); // straight to a screen of an app that supports itdroidline chrome.go droidline.dev
droidline open_url https://droidline.dev/docs/Deep links are often the only way to reach a screen that launch cannot open directly. Screens that other apps may open by an intent action, such as Settings pages, open with intent; the Settings recipes use it.
Wait for a code in a notification
First allow the app's notifications to reach the PC (once, with notify_filter or on the app's Status tab). Then wait for the message and pull the digits out:
import re
d.notify_filter(["com.google.android.apps.messaging"])
n = d.wait_notification("textContains", "code", 120)
code = re.search(r"\d{4,8}", n["text"]).group()
d.input("id", "otp", code)await d.notifyFilter(["com.google.android.apps.messaging"]);
const n = await d.waitNotification("textContains", "code", 120);
const code = n.text.match(/\d{4,8}/)[0];
await d.input("id", "otp", code);using System.Text.RegularExpressions;
await d.NotifyFilterAsync(new[] { "com.google.android.apps.messaging" });
var n = await d.WaitNotificationAsync("textContains", "code", 120);
var code = Regex.Match(n.Get<string>("text") ?? "", @"\d{4,8}").Value;
await d.InputAsync("id", "otp", code);code=$(droidline --json wait_notification textContains code 120 | jq -r '.value.text' | grep -oE '[0-9]{4,8}' | head -1)
droidline input id otp "$code"Copy and paste through the clipboard
d.clipboard("text to paste")
d.long_touch("id", "message") # the field's menu offers Paste
d.touch("text", "Paste")
print(d.clipboard()) # read it backawait d.clipboard("text to paste");
await d.longTouch("id", "message");
await d.touch("text", "Paste");
console.log(await d.clipboard());await d.ClipboardAsync("text to paste");
await d.LongTouchAsync("id", "message"); // the field's menu offers Paste
await d.TouchAsync("text", "Paste");
Console.WriteLine(await d.ClipboardAsync()); // read it backdroidline clipboard "text to paste"
droidline clipboardReading the clipboard on Android 10 and later needs the Droidline keyboard to be the current keyboard.
Settings: force stop, clear data, network switches
Force stopping an app, clearing its data, and switching Wi-Fi, mobile data or airplane mode all happen in Android's Settings app. intent opens the right Settings screen directly, and ordinary commands press the buttons. These are recipes instead of commands because Settings differs by phone maker, Android version and system language.
The recipes share a few selectors. textMatches takes a regular expression, so one pattern can hold a label in several languages. android:id/button1 is the standard confirm button of Android dialogs and has the same id in every language.
FORCE_STOP = {"textMatches": "Force stop|강제 중지|强行停止"}
STORAGE = {"textMatches": "Storage.*|저장공간.*|存储.*"}
CLEAR = {"textMatches": "Clear (data|storage)|데이터 삭제|清除(数据|存储空间)"}
OK = ("id", "android:id/button1") # the confirm button of Android dialogs, in any languageconst FORCE_STOP = { textMatches: "Force stop|강제 중지|强行停止" };
const STORAGE = { textMatches: "Storage.*|저장공간.*|存储.*" };
const CLEAR = { textMatches: "Clear (data|storage)|데이터 삭제|清除(数据|存储空间)" };
const OK = ["id", "android:id/button1"]; // the confirm button of Android dialogs, in any languagevar forceStop = new { textMatches = "Force stop|강제 중지|强行停止" };
var storage = new { textMatches = "Storage.*|저장공간.*|存储.*" };
var clear = new { textMatches = "Clear (data|storage)|데이터 삭제|清除(数据|存储空间)" };
var ok = new { id = "android:id/button1" }; // the confirm button of Android dialogs, in any languageFORCE_STOP='{"textMatches":"Force stop|강제 중지|强行停止"}'
STORAGE='{"textMatches":"Storage.*|저장공간.*|存储.*"}'
CLEAR='{"textMatches":"Clear (data|storage)|데이터 삭제|清除(数据|存储空间)"}'Force stop an app
android.settings.APPLICATION_DETAILS_SETTINGS opens an app's info page. A greyed-out Force stop button means the app is not running, so there is nothing to stop:
def force_stop(d, package):
d.intent("android.settings.APPLICATION_DETAILS_SETTINGS", "package:" + package)
d.wait_idle()
button = d.find(FORCE_STOP)
if button["enabled"]: # greyed out when the app is not running
button.click()
d.touch(*OK)async function forceStop(d, pkg) {
await d.intent("android.settings.APPLICATION_DETAILS_SETTINGS", "package:" + pkg);
await d.waitIdle();
const button = await d.find(FORCE_STOP);
if (button.node.enabled) { // greyed out when the app is not running
await button.click();
await d.touch(...OK);
}
}async Task ForceStopAsync(Device d, string package)
{
await d.IntentAsync("android.settings.APPLICATION_DETAILS_SETTINGS", "package:" + package);
await d.WaitIdleAsync();
var button = await d.FindAsync(forceStop);
if (button["enabled"] is true) // greyed out when the app is not running
{
await button.ClickAsync();
await d.TouchAsync(ok);
}
}droidline intent android.settings.APPLICATION_DETAILS_SETTINGS package:com.example.shop
droidline wait_idle
if [ "$(droidline --json find "$FORCE_STOP" | jq -r '.value.enabled')" = "true" ]; then
droidline touch "$FORCE_STOP"
droidline touch id android:id/button1
fiClear an app's data
This wipes logins and settings too. In device owner mode, clear_data(package) does it directly without opening Settings. Without device owner mode, go through the app's storage page:
def clear_data(d, package): # in device owner mode, d.clear_data(package) does this directly
d.intent("android.settings.APPLICATION_DETAILS_SETTINGS", "package:" + package)
d.wait_idle()
d.scroll_to(STORAGE)
d.touch(STORAGE)
d.wait_idle()
d.touch(CLEAR)
d.touch(*OK)async function clearData(d, pkg) { // in device owner mode, d.clearData(pkg) does this directly
await d.intent("android.settings.APPLICATION_DETAILS_SETTINGS", "package:" + pkg);
await d.waitIdle();
await d.scrollTo(STORAGE);
await d.touch(STORAGE);
await d.waitIdle();
await d.touch(CLEAR);
await d.touch(...OK);
}// in device owner mode, d.ClearDataAsync(package) does this directly
async Task ClearDataAsync(Device d, string package)
{
await d.IntentAsync("android.settings.APPLICATION_DETAILS_SETTINGS", "package:" + package);
await d.WaitIdleAsync();
await d.ScrollToAsync(storage);
await d.TouchAsync(storage);
await d.WaitIdleAsync();
await d.TouchAsync(clear);
await d.TouchAsync(ok);
}droidline intent android.settings.APPLICATION_DETAILS_SETTINGS package:com.example.shop
droidline wait_idle
droidline scroll_to "$STORAGE"
droidline touch "$STORAGE"
droidline wait_idle
droidline touch "$CLEAR"
droidline touch id android:id/button1Some apps, such as Chrome, show Manage space on their storage page instead of a clear button. Clear those inside the app, or use device owner mode.
Turn Wi-Fi off and on
While its network is off, the phone cannot hear commands. Keep off and on in one batch and pass cuts_network=True: the phone answers {"accepted": true} first, runs the steps on its own while offline, and the result arrives after it reconnects. With wait=True the call waits for that result instead. Concepts explains this in more detail.
d.intent("android.settings.WIFI_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.WIFI_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.WIFI_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 intent android.settings.WIFI_SETTINGS
droidline wait_idle
SWITCH='["touch",{"class":"android.widget.Switch","visible":true}]'
droidline batch "[$SWITCH,[\"sleep\",3000],$SWITCH]" --cuts_network --waitTurn mobile data off and on
Samsung phones ask for confirmation both when mobile data goes off and when it comes back on, so the batch presses the dialog's confirm button after each switch. On phones that do not ask, drop the ok steps:
d.intent("android.settings.DATA_USAGE_SETTINGS")
d.wait_idle()
data = {"class": "android.widget.Switch", "row": {"textMatches": "Mobile data|모바일 데이터|移动数据"}}
ok = ("touch", "id", "android:id/button1")
d.batch([("touch", data), ok, ("sleep", 3000), ("touch", data), ok], cuts_network=True, wait=True)await d.intent("android.settings.DATA_USAGE_SETTINGS");
await d.waitIdle();
const data = { class: "android.widget.Switch", row: { textMatches: "Mobile data|모바일 데이터|移动数据" } };
const ok = ["touch", "id", "android:id/button1"];
await d.batch([["touch", data], ok, ["sleep", 3000], ["touch", data], ok], { cuts_network: true, wait: true });await d.IntentAsync("android.settings.DATA_USAGE_SETTINGS");
await d.WaitIdleAsync();
var data = new { @class = "android.widget.Switch", row = new { textMatches = "Mobile data|모바일 데이터|移动数据" } };
var ok = ("touch", "id", "android:id/button1");
await d.BatchAsync(new object[] { ("touch", data), ok, ("sleep", 3000), ("touch", data), ok }, cutsNetwork: true, wait: true);droidline intent android.settings.DATA_USAGE_SETTINGS
droidline wait_idle
DATA='["touch",{"class":"android.widget.Switch","row":{"textMatches":"Mobile data|모바일 데이터|移动数据"}}]'
OK='["touch","id","android:id/button1"]'
droidline batch "[$DATA,$OK,[\"sleep\",3000],$DATA,$OK]" --cuts_network --waitGet a new mobile IP address
On mobile data, turning airplane mode on and off usually makes the carrier assign a new address. It is the Wi-Fi recipe on the airplane mode page:
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)
print(d.network()) # {'type': 'mobile', 'airplane': False, 'metered': 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 });
console.log(await d.network());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);
Console.WriteLine(await d.NetworkAsync());droidline intent android.settings.AIRPLANE_MODE_SETTINGS
droidline wait_idle
SWITCH='["touch",{"class":"android.widget.Switch","visible":true}]'
droidline batch "[$SWITCH,[\"sleep\",3000],$SWITCH]" --cuts_network --waitIf the first switch on that page is not airplane mode on your phone, select the switch by its row instead, as in the mobile data recipe. The phone reconnects to the PC by itself once airplane mode is off.
Run the same steps on every phone
from concurrent.futures import ThreadPoolExecutor
from droidline import Droidline
dl = Droidline()
names = [p["name"] for p in dl.devices() if p["online"]]
def job(name):
d = dl.device(name)
d.launch("com.android.chrome")
return name, d.current()["package"]
with ThreadPoolExecutor(len(names) or 1) as pool:
print(list(pool.map(job, names)))import { Droidline } from "droidline";
const dl = new Droidline();
const online = (await dl.devices()).filter((p) => p.online);
console.log(await Promise.all(online.map(async (p) => {
const d = dl.device(p.name);
await d.launch("com.android.chrome");
return [p.name, (await d.current()).package];
})));using Droidline;
using var client = new DroidlineClient();
var online = (await client.DevicesAsync()).Where(p => p.Get<bool>("online"));
var results = await Task.WhenAll(online.Select(async p =>
{
var d = client.Device(p.Get<string>("name"));
await d.LaunchAsync("com.android.chrome");
return (p.Get<string>("name"), (await d.CurrentAsync()).Package);
}));
Console.WriteLine(string.Join(", ", results));for name in $(droidline --json devices | jq -r '.value[] | select(.online) | .name'); do
droidline -d "$name" launch com.android.chrome &
done
waitMany phones goes further: naming, per-phone proxies and keeping a shelf healthy.