2012-02-10 103 views
0

我想從android應用程序執行shell腳本。我能夠通過像ls pwd date等命令:如何在android應用程序中包含shell腳本

process p = Runtime.getRuntime.exec(「command」);

但現在我想執行我的應用程序所需的shell腳本。 shell腳本在linux終端上正常工作。

你能幫助我幫助我在哪裏存儲shell腳本以及如何從程序調用它?

首先可能嗎?

+0

我發現您的權限得到了在shell命令是有限的。你可以在'adb shell'中執行的命令不能在'Runtime.exec'中執行。有人可以解釋嗎? – 2012-02-10 07:40:32

回答

0

從android應用程序執行任意shell腳本聽起來像個壞主意 - 但您應該可以將shell腳本放在SD卡上並通過將完整路徑傳遞到SD卡上的文件來執行它。

Environment.getExternalStorageDirectory().getAbsolutePath() 

將爲您提供SD卡的完整路徑。檢查以確保它首先安裝在:

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) 
+0

這是一個好主意..我可以想象它的工作.. 但是有沒有辦法使用sdk,可能包括資產文件夾中的shell腳本或者像添加jar文件等,這使得它方便分發應用程序? – 2012-02-10 06:05:22

+0

你可以做到這一點。您可以像訪問其他任何內容一樣從您的APK中訪問內容。一種方法是將整個shell腳本作爲一個字符串加入,並將其從字符串xml中輸出。另一種將它作爲資源包含並加載的方法。關於SD卡方法的好處是用戶可以通過將腳本掛載到他們的計算機上來修改/查看腳本。 – debracey 2012-02-11 21:14:14

+0

非常感謝....現在試試吧...... – 2012-02-14 04:36:06

0

如果可能,我會強烈建議使用Java和Android SDK來複制腳本的功能。

否則,我認爲你需要root,那麼你需要做同樣的事情到this

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

確實4it支持管道嗎?當我嘗試runtime.getRuntime.exec(「date | cut -d /」/「-f 1」)它沒有工作。 – 2012-02-10 06:27:25

相關問題