android - 如何在 android studio 中监听 shell 命令的响应?
问题描述
在 android 终端模拟器中,我可以键入以下命令:
> su
> echo $(</sys/class/power_supply/battery/charge_rate)
并且根据手机的充电方式,输出将是“无”、“正常”或“涡轮”。我希望能够检索此输出并将其作为字符串值存储在我的程序中。
所以我对此做了一些研究,我想出的代码如下:
String chargeRate = "None";
try {
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("su \"\"echo $(</sys/class/power_supply/battery/charge_rate)");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
if ((chargeRate = stdInput.readLine()) == null)
chargeRate = "None";
}
catch (Exception e) {
// TODO
}
这是从许多不同的答案中得出的,我不太确定它有什么问题。调试时我不能越过或越过这条线:
if ((chargeRate = stdInput.readLine()) == null)
一旦调试器到达这一行,它就会说“应用程序正在运行”
解决方案
更新:解决方案是无法使用 Runtime.exec() 在 Android Java 代码中执行 shell 命令“echo”:
Runtime.getRuntime.exec()
不直接执行 shell 命令,它执行带有参数的可执行文件。"echo" 是一个内置的 shell 命令。它实际上是带有选项 -c 的可执行文件 sh 的参数的一部分。像这样的命令ls
是实际的可执行文件。您可以在 adb shell 中使用type echo
和type ls
命令来查看差异。所以最终代码是:
String[] cmdline = { "sh", "-c", "echo $..." };
Runtime.getRuntime().exec(cmdline);
cat
也可以从内部执行Runtime.exec()
而无需调用sh
这也在https://www.javaworld.com/article/2071275/when-runtime-exec---won-t.html?page=2段落中进行了分析假设命令是可执行程序
Execute shell commands and get output in a TextView中的代码很好,尽管它使用的是可直接执行的命令(ls
参见上面的更新):
try {
// Executes the command.
Process process = Runtime.getRuntime().exec("ls -l");
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
推荐阅读
- angular-material - 如何更改 angular-material 版本 9 表单控件的新默认背景颜色?
- kotlin - 如何在 Kotlin 中嵌套多个属性委托
- java - 如何让 clojure 写入对套接字的响应?
- apache-kafka - 处理Kafka中消息的重复和顺序
- python-3.x - Python 将多列合二为一
- java - 处理文件后通过 SftpOutboundGateway 删除文件
- html - 在R中将动态url转换为静态
- adaptive-cards - 在 Adaptive Cards 中,如何使用数据绑定到模板来创建表?
- c# - Python 解密与 .NET 加密不匹配
- c - 在将数组传递给函数时,我无法让气泡排序在函数中工作