【发布时间】:2023-12-11 12:22:01
【问题描述】:
谁能说adb命令是否可以通过我的android应用程序执行。如果可以执行,如何实现?
【问题讨论】:
-
你找到在设备上运行 adb 的方法了吗?我只收到消息:错误:在设备上直接运行 adb 时找不到设备
谁能说adb命令是否可以通过我的android应用程序执行。如果可以执行,如何实现?
【问题讨论】:
你可以这样做:
Process process = Runtime.getRuntime().exec("your command");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
不要忘记用 try and catch 语句包围它。
编辑:
@Phix 是对的,ProcessBuilder 会更好用。
【讨论】:
Runtime.getRuntime() 已被搁置。 *.com/questions/7069425/…
普通 Android 应用程序对通过 adb 启动的进程具有不同的权限,例如,允许通过 adb 启动的进程捕获屏幕,而普通应用程序则不允许。因此,您可以通过Runtime.getRuntime().exec() 从您的应用程序执行命令,但它们不会拥有与您从adb shell 执行的权限相同的权限。
【讨论】:
我发现这篇文章是为了寻找不同的查询,但我之前专门在 android 上与 input 合作过,所以我想澄清一下这个问题。
原因
Runtime.getRuntime().exec("adb shell input keyevent 120");
不工作,是因为你没有删除
adb shell
ADB 部分仅用于您的计算机,如果您没有正确安装 ADB,该命令实际上是您计算机上 adb.exe 文件的路径,如下所示
C:\XXXX\ADB Files\adb.exe shell
或
C:\XXXX\ADB 文件\adb shell
shell 部分告诉您计算机上的 ADB 程序访问设备外壳,因此您的设备也不知道外壳是什么...
使用sh /path/to/commandList.sh 将执行commandList.sh 中列出的命令,因为它是一个shell 脚本(Windows 上的.batch 文件类似)
你要使用的命令是
Runtime.getRuntime().exec("input keyevent 120");
但是这会导致环境为空且工作目录为空,您可以通过将命令写入 shell 脚本(.sh 文件)然后使用
运行脚本来绕过此问题Runtime.getRuntime().exec("sh path/to/shellScript.sh");
有时不需要sh,但我只是使用它。
我希望这至少能解决一些问题:)
【讨论】:
在 Runtime.getRuntime().exec 中调用的 adb shell 未在 shell 用户下运行。它提供 shell 但具有相同的进程所有者用户(如 u0_a44)。这就是所有命令都不起作用的原因。
【讨论】:
这就是我在 Kotlin 中所做的,我也得到命令响应
fun runShellCommand(command: String) {
// Run the command
val process = Runtime.getRuntime().exec(command)
val bufferedReader = BufferedReader(
InputStreamReader(process.inputStream)
)
// Grab the results
val log = StringBuilder()
var line: String?
line = bufferedReader.readLine()
while (line != null) {
log.append(line + "\n")
line = bufferedReader.readLine()
}
val Reader = BufferedReader(
InputStreamReader(process.errorStream)
)
// if we had an error during ex we get here
val error_log = StringBuilder()
var error_line: String?
error_line = Reader.readLine()
while (error_line != null) {
error_log.append(error_line + "\n")
error_line = Reader.readLine()
}
if (error_log.toString() != "")
Log.info("ADB_COMMAND", "command : $command $log error $error_log")
else
Log.info("ADB_COMMAND", "command : $command $log")
}
【讨论】:
执行
Runtime.getRuntime().exec("adb shell input keyevent 120");
我收到以下错误: java.io.IOException:无法运行程序“adb”:错误=13,权限被拒绝。
执行中
Runtime.getRuntime().exec("adb shell input keyevent 120");
没有错误,但同时我的截图请求没有处理。
我发现这在早期版本的 android 中有效,但后来它被删除了。虽然我无法在这里提供它为什么不起作用的来源。
希望这可以帮助像我这样尝试使用这种方法在应用不在前台时截取屏幕截图的人。
【讨论】:
android.permission.DUMP
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
string cmd = "/system/bin/input keyevent 23\n";
os.writeBytes(cmd);
手机必须root。在这里,我执行了 adb 命令“input keyevent 23”。 记住当你通过 su 执行 adb 命令时,你不需要添加“adb shell input keyevent 23”
【讨论】: