2010-09-27 59 views

回答

8

這段代碼需要root訪問權限,但將執行給定String作爲一個shell命令

void execCommandLine(String command) 
{ 
    Runtime runtime = Runtime.getRuntime(); 
    Process proc = null; 
    OutputStreamWriter osw = null; 

    try 
    { 
     proc = runtime.exec("su"); 
     osw = new OutputStreamWriter(proc.getOutputStream()); 
     osw.write(command); 
     osw.flush(); 
     osw.close(); 
    } 
    catch (IOException ex) 
    { 
     Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command); 
     return; 
    } 
    finally 
    { 
     if (osw != null) 
     { 
      try 
      { 
       osw.close(); 
      } 
      catch (IOException e){} 
     } 
    } 

    try 
    { 
     proc.waitFor(); 
    } 
    catch (InterruptedException e){} 

    if (proc.exitValue() != 0) 
    { 
     Log.e("execCommandLine()", "Command returned error: " + command + "\n Exit code: " + proc.exitValue()); 
    } 
} 
+0

太感謝你了......你會被要求修改此運行多個shell命令? – 2010-09-27 22:08:16

+0

最壞的情況下,您可以爲每個命令調用此函數,但應該能夠將每個命令與換行符分隔開\ n – 2010-09-27 22:40:32

相關問題