从应用程序运行 shell 命令 [Rooted]

2024-02-07

在我的应用程序中,我想运行一些 shell 命令并解释输出。这些命令本质上是在 root 手机上运行的命令。

我该怎么做?


首先确保您需要的 shell 命令在 Android 中确实可用。我假设您可以执行诸如重定向输出之类的操作,从而遇到了问题>.

此方法也适用于我相信 v2.2 的非 root 手机,但您应该检查 API 参考以确保确定。

try {
        Process chmod = Runtime.getRuntime().exec("/system/bin/chmod 777 " +fileName);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(nfiq.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();
        chmod.waitFor();
        outputString =  output.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

虽然可能不是 100% 必要,但最好让进程使用 process.waitFor() 等待 exec 完成,因为您说过您关心输出。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从应用程序运行 shell 命令 [Rooted] 的相关文章

随机推荐