首页 > 解决方案 > 如何在 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)

一旦调试器到达这一行,它就会说“应用程序正在运行”

标签: androidshellioroot

解决方案


更新:解决方案是无法使用 Runtime.exec() 在 Android Java 代码中执行 shell 命令“echo”

Runtime.getRuntime.exec()不直接执行 shell 命令,它执行带有参数的可执行文件。"echo" 是一个内置的 shell 命令。它实际上是带有选项 -c 的可执行文件 sh 的参数的一部分。像这样的命令ls是实际的可执行文件。您可以在 adb shell 中使用type echotype 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);
    }

推荐阅读