Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从应用程序[根目录]运行shell命令_Android_Root - Fatal编程技术网

Android 从应用程序[根目录]运行shell命令

Android 从应用程序[根目录]运行shell命令,android,root,Android,Root,在我的应用程序中,我想运行几个shell命令并解释输出。这些命令本质上是在根手机上运行的 如何操作?您需要首先确保已安装busybox,因为这将安装最常用的shell命令列表,然后使用以下代码运行该命令 Runtime.getRuntime().exec("ls"); 首先,确保您需要的shell命令在Android中实际可用。我遇到了一些问题,因为我假设您可以使用重定向输出 此方法也适用于我相信v2.2的非根手机,但您应该检查API参考以确保 try { Process ch

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


如何操作?

您需要首先确保已安装busybox,因为这将安装最常用的shell命令列表,然后使用以下代码运行该命令

Runtime.getRuntime().exec("ls");

首先,确保您需要的shell命令在Android中实际可用。我遇到了一些问题,因为我假设您可以使用重定向输出

此方法也适用于我相信v2.2的非根手机,但您应该检查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%必需的,但最好让进程等待exec完成process.waitFor(),因为您说过您关心输出

有些命令是这样工作的(top等),但另一些命令返回一个空字符串,即使当我从adb shell运行命令时它输出到终端。例如,process=Runtime.getRuntime().exec(“/system/bin/ping”);知道为什么输入流上什么都没有吗?啊,两个不同的问题。我使用readLine()获取“top”的输出,但是“top”的输出中的第一件事是换行符,因此可以解释空字符串。另一件事是“ping”产生了错误,它们在getErrorStream()而不是getInputStream()中。现在一切都好了:)