2011-07-23 33 views

回答

5

首先确保您需要的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(),因为你说你关心的输出完成。

+0

一些命令像这样(顶部等)工作,但其他返回一个空字符串,即使它从我的外壳程序运行命令时输出到终端。例如。 process = Runtime.getRuntime()。exec(“/ system/bin/ping”);任何想法为什么输入流中没有任何内容? –

+1

啊,两个不同的问题。我使用readLine()来获取'top'的输出,但'top'输出中的第一件事是一个换行符,这样就解释了空字符串。另一件事是'ping'产生错误,并且它们在getErrorStream()而不是getInputStream()中。一切都很好:) –

2

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

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