【问题标题】:How do I listen for a response from shell command in android studio?如何在 android studio 中监听 shell 命令的响应?
【发布时间】:2020-04-26 02:04:13
【问题描述】:

在安卓终端模拟器中,我可以输入以下命令:

> 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)

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

【问题讨论】:

标签: android shell io root


【解决方案1】:

更新:解决方案在 Unable using Runtime.exec() to execute shell command "echo" in Android Java code

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

【讨论】:

  • 不幸的是,该代码给了我与原始代码相同的反应,我将查看您喜欢的那个问题帖子。感谢您的帮助
  • 在我的手机上echo 不起作用,对我来说即使没有su 也可以工作cat /sys/class/power_supply/battery/batt_temp。在您的情况下,echo 命令似乎没有返回,请参阅stackoverflow.com/questions/5483830/…
  • 这可能是权限/安全问题(命令注入),请参阅stackoverflow.com/questions/11268189/…security.stackexchange.com/questions/152792/… 并检查您应用的权限
  • 更新答案中的问题链接很有用,谢谢
  • 对于其他任何人,我确实需要将命令数组更改为 String[] cmdline = { "su", "sh", "-c", "echo $..." };因为我需要 SU 权限
猜你喜欢
  • 1970-01-01
  • 2018-11-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2011-08-14
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多