您能否使用ADB从计算机直接在安卓设备上输入文字?如果可以,怎样实现?
adb shell input keyevent KEYCODE
或者 adb shell input text "mytext"
。所有按键代码列表都可以在 这里 找到。adb shell input text "text"
,其中文本可以包含 %s
以表示空格。 - piojo正如Manuel所说,您可以使用adb shell input text
,但是您需要将空格替换为%s
,并处理引号。这里有一个简单的bash脚本,使这个过程变得非常容易:
#!/bin/bash
text=$(printf '%s%%s' ${@}) # concatenate and replace spaces with %s
text=${text%%%s} # remove the trailing %s
text=${text//\'/\\\'} # escape single quotes
text=${text//\"/\\\"} # escape double quotes
# echo "[$text]" # debugging
adb shell input text "$text"
将文件保存为atext
,并设置为可执行。然后您就可以不用引号调用脚本...
atext Hello world!
...除非您需要发送引号,否则您需要将它们放在另一种引号之间(这是 shell 的限制):
atext "I'd" like it '"shaken, not stirred"'
#!/bin/bash
escape_text()
{
printf '%s' "$1" | sed -e 's/[]['\''\"&;()|$]/\\&/g'
}
text=$(printf '%s%%s' ${@}) # 连接并将空格替换为%s
text=${text%%%s} # 删除尾部的%s
text=$(escape_text "$text")
echo "Text = $text" # 调试
- Borderless.Nomad为了避免文本参数的扩展/评估(即对于类似于“$”或“;”等特殊字符),您可以像这样将它们包装在引号中:
adb shell "input text 'insert your text here'"
这里有一个基于 Bash
的解决方案,适用于任意/复杂字符串(例如随机密码)。这里提供的其他解决方案在这方面都没有成功:
#!/usr/bin/env bash
read -r -p "Enter string: " string # prompt user to input string
string="${string// /%s}" # replace spaces in string with '%s'
printf -v string "%q" "${string}" # quote string in a way that allows it to be reused as shell input
adb shell input text "${string}" # input string on device via adb
#!/usr/bin/env bash
echo
echo "Hit CTRL+D or CTRL+C to exit."
echo
while true; do
read -r -p "Enter string: " string || { echo "^D"; break; }
string="${string// /%s}"
printf -v string "%q" "${string}"
echo "Sending string via adb..."
adb shell input text "${string}"
done
$ adb shell input text ö
Killed
input
限制。#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from com.dtmilano.android.viewclient import ViewClient
vc = ViewClient(*ViewClient.connectToDeviceOrExit(), useuiautomatorhelper=True)
oid = vc.uiAutomatorHelper.ui_device.find_object(clazz='android.widget.EditText').oid
vc.uiAutomatorHelper.ui_object2.set_text(oid, '你好世界 ')
EditText
,然后输入一些中文字符和表情符号。如果你只需要输入文本,你可以使用bash
和curl
来实现相同的功能。#! /bin/bash
#
# simple-input-text
# - Finds an EditText
# - Enters text
#
# prerequisites:
# - adb finds and lists the device
# - ./culebratester2 start-server
# - jq installed (https://stedolan.github.io/jq/)
#
set -e
set +x
base_url=http://localhost:9987/v2/
do_curl() {
curl -sf -H "accept: application/json" -H "Content-Type: application/json" "$@"
}
oid=$(do_curl -X POST "${base_url}/uiDevice/findObject" \
-d "{'clazz': 'android.widget.EditText'}" | jq .oid)
do_curl -X POST "${base_url}/uiObject2/${oid}/setText" \
-d "{'text': '你好世界 '}"
使用zsh时,这是一个更强大的将文本发送到Android设备的函数:
function adbtext() {
while read -r line; do
adb shell input text ${(q)${line// /%s}}
done
}
虽然Zsh引用可能与常规的POSIX shell略有不同,但我没有发现它无法使用的任何内容。例如,Dan的答案缺少需要转义的>
。
我正在使用它与pass show ... | adbtext
一起使用。
你可以在talkmyphone中看到它是如何完成的。
他们正在使用Jabber
,但这可能对你有用。
inout
不支持的字符需要考虑的一些事项:https://dev59.com/f2Yq5IYBdhLWcg3wwDNA#14273689 - Diego Torres Milano