1. 程式人生 > >Android: 通過Runtime.getRuntime().exec呼叫底層Linux下的程式或指令碼

Android: 通過Runtime.getRuntime().exec呼叫底層Linux下的程式或指令碼

Android Runtime使得直接呼叫底層Linux下的可執行程式或指令碼成為可能

比如Linux下寫個測試工具,直接編譯後apk中通過Runtime來呼叫

或者寫個指令碼,apk中直接呼叫,省去中間層或者JNI

這個至少效率應該比較高吧

 

程式碼:

  1. publicclass test extends Activity {  
  2.     TextView text;  
  3.     /** Called when the activity is first created. */
  4.     @Override
  5.     publicvoid onCreate(Bundle savedInstanceState) {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.main);  
  8.         text = (TextView) findViewById(R.id.text);  
  9.         Button btn_ls = (Button) findViewById(R.id.btn_ls);  
  10.         btn_ls.setOnClickListener(new OnClickListener() {  
  11.             publicvoid onClick(View v) {                 
  12.                 do_exec("ls /mnt/sdcard");  
  13.             }             
  14.         });  
  15.         Button btn_cat = (Button) findViewById(R.id.btn_cat);  
  16.         btn_cat.setOnClickListener(new OnClickListener() {  
  17.             publicvoid onClick(View v) {                 
  18.                 do_exec("cat /proc/version"
    );  
  19.             }             
  20.         });          
  21.         Button btn_rm = (Button) findViewById(R.id.btn_rm);  
  22.         btn_rm.setOnClickListener(new OnClickListener() {  
  23.             publicvoid onClick(View v) {                 
  24.                 do_exec("rm /mnt/sdcard/1.jpg");  
  25.             }             
  26.         });      
  27.         Button btn_sh = (Button) findViewById(R.id.btn_sh);  
  28.         btn_sh.setOnClickListener(new OnClickListener() {  
  29.             publicvoid onClick(View v) {                 
  30.                 do_exec("/system/bin/sh /mnt/sdcard/test.sh 123");  
  31.             }             
  32.         });           
  33.     }  
  34.     String do_exec(String cmd) {  
  35.         String s = "/n";  
  36.         try {  
  37.             Process p = Runtime.getRuntime().exec(cmd);  
  38.             BufferedReader in = new BufferedReader(  
  39.                                 new InputStreamReader(p.getInputStream()));  
  40.             String line = null;  
  41.             while ((line = in.readLine()) != null) {  
  42.                 s += line + "/n";                 
  43.             }  
  44.         } catch (IOException e) {  
  45.             // TODO Auto-generated catch block
  46.             e.printStackTrace();  
  47.         }  
  48.         text.setText(s);  
  49.         return cmd;       
  50.     }  
  51. }  

test.sh:

echo test.sh
echo $1

需要注意:

1. exec不等於console命令

2. exec的輸入輸出流需要自己處理

3. exec執行時阻塞、非阻塞,返回結果問題

4. 注意許可權問題 

有個文章講的比較深入,貼出來研究: