本文介绍了从应用程序运行 shell 命令 [Rooted]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想运行几个 shell 命令并解释输出.这些命令本质上是可以在有 root 权限的手机上运行的.

In my app, I want to run few shell command sand interpret the output. These commands are essentially the on that would run on rooted phone.

我该怎么做?

推荐答案

首先确保您需要的 shell 命令在 Android 中实际可用.假设您可以使用 > 执行重定向输出等操作,我遇到了一些问题.

First make sure that the shell command that you need is actually available in Android. I've run into issues by assuming you can do things like redirect output with >.

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

This method also works on non-rooted phones of I believe v2.2, but you should check the API reference to be sure.

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% 必要,但最好让进程等待 exec 使用 process.waitFor() 完成,因为您说过您关心输出.

While it's probably not 100% necessary, it's a good idea to have the process wait for the exec to complete with process.waitFor() since you said that you care about the output.

这篇关于从应用程序运行 shell 命令 [Rooted]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 03:20