首页 > 解决方案 > 在 Android Studio 上运行终端命令

问题描述

我正在尝试制作一个允许我切换手机缩放调节器的应用程序(是的,我已经扎根了)。经过大量搜索,我发现我通常需要运行命令关闭process = Runtime.getRuntime().exec(cmd);

但是,经过多次尝试,该应用程序似乎没有正确响应。到目前为止,这是我的代码。

    String RunCommand(String cmd) {
    StringBuffer cmdOut = new StringBuffer();
    Process process;
    try{
        process = Runtime.getRuntime().exec(cmd);
        InputStreamReader r = new InputStreamReader(process.getInputStream());
        BufferedReader bufReader = new BufferedReader(r);
        char[] buf = new char[4096];
        int nRead = 0;
        while ((nRead = bufReader.read(buf)) > 0){
            cmdOut.append(buf, 0, nRead);
        }
        bufReader.close();
        try {
            process.waitFor();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }catch (IOException e) {
        e.printStackTrace();
    }
    return cmdOut.toString();
}

事实上,我不需要输出文件,因为我正在运行的命令实际上并不需要输出。IEecho performance > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

当我运行该应用程序时,它要么挂起,要么什么都不做。不知道我做错了什么?非常感谢任何帮助!

标签: androidshellandroid-studioterminalruntime.exec

解决方案


这是我用于我的应用程序的代码:

fun sudo(vararg strings: String) {
    try {
        val su = Runtime.getRuntime().exec("su")
        val outputStream = DataOutputStream(su.outputStream)

        for (s in strings) {
            outputStream.writeBytes(s + "\n")
            outputStream.flush()
        }

        outputStream.writeBytes("exit\n")
        outputStream.flush()
        try {
            su.waitFor()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        outputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }

}

它在 Kotlin 中,但很容易转换为 Java。

我相信,关键部分是exec()su. 然后,该函数将您发送的命令写入 OutputStream,以便在su进程下运行它们。

如果您的应用程序挂起,请确保您使用您使用的任何管理器(Magisk、SuperSU 等)授予它 root 访问权限。


推荐阅读