在 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)
一旦调试器到达此行,它就会显示“应用程序正在运行”
UPDATE: 解决方案在无法使用 Runtime.exec() 在 Android Java 代码中执行 shell 命令“echo” https://stackoverflow.com/questions/25199307/unable-using-runtime-exec-to-execute-shell-command-echo-in-android-java-code :
Runtime.getRuntime.exec()
不直接执行 shell 命令,
它执行带有参数的可执行文件。 “echo”是一个内置 shell
命令。它实际上是可执行文件 sh 参数的一部分
使用选项 -c。命令如ls
是实际的可执行文件。你可以
使用type echo
and type ls
在 adb shell 中命令查看
不同之处。
所以最终的代码是:
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 https://www.javaworld.com/article/2071275/when-runtime-exec---won-t.html?page=2在段落中假设命令是可执行程序
代码在执行 shell 命令并在 TextView 中获取输出 https://stackoverflow.com/questions/23608005/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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)