經過Runtime.getRuntime().exec調用底層Linux下的程序或腳本

Android Runtime使得直接調用底層Linux下的可執行程序或腳本成爲可能java

好比Linux下寫個測試工具,直接編譯後apk中經過Runtime來調用ide

或者寫個腳本,apk中直接調用,省去中間層或者JNI工具

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

 

 

代碼:spa

[java] view plaincopy.net

  1. public class test extends Activity {  blog

  2.     TextView text;  get

  3.       

  4.     /** Called when the activity is first created. */  cmd

  5.     @Override  it

  6.     public void onCreate(Bundle savedInstanceState) {  

  7.         super.onCreate(savedInstanceState);  

  8.         setContentView(R.layout.main);  

  9.           

  10.         text = (TextView) findViewById(R.id.text);  

  11.           

  12.         Button btn_ls = (Button) findViewById(R.id.btn_ls);  

  13.         btn_ls.setOnClickListener(new OnClickListener() {  

  14.             public void onClick(View v) {                 

  15.                 do_exec("ls /mnt/sdcard");  

  16.             }             

  17.         });  

  18.         Button btn_cat = (Button) findViewById(R.id.btn_cat);  

  19.         btn_cat.setOnClickListener(new OnClickListener() {  

  20.             public void onClick(View v) {                 

  21.                 do_exec("cat /proc/version");  

  22.             }             

  23.         });          

  24.         Button btn_rm = (Button) findViewById(R.id.btn_rm);  

  25.         btn_rm.setOnClickListener(new OnClickListener() {  

  26.             public void onClick(View v) {                 

  27.                 do_exec("rm /mnt/sdcard/1.jpg");  

  28.             }             

  29.         });      

  30.         Button btn_sh = (Button) findViewById(R.id.btn_sh);  

  31.         btn_sh.setOnClickListener(new OnClickListener() {  

  32.             public void onClick(View v) {                 

  33.                 do_exec("/system/bin/sh /mnt/sdcard/test.sh 123");  

  34.             }             

  35.         });           

  36.     }  

  37.       

  38.     String do_exec(String cmd) {  

  39.         String s = "/n";  

  40.         try {  

  41.             Process p = Runtime.getRuntime().exec(cmd);  

  42.             BufferedReader in = new BufferedReader(  

  43.                                 new InputStreamReader(p.getInputStream()));  

  44.             String line = null;  

  45.             while ((line = in.readLine()) != null) {  

  46.                 s += line + "/n";                 

  47.             }  

  48.         } catch (IOException e) {  

  49.             // TODO Auto-generated catch block  

  50.             e.printStackTrace();  

  51.         }  

  52.         text.setText(s);  

  53.         return cmd;       

  54.     }  

  55. }  

 

test.sh:

echo test.sh
echo $1

 

須要注意:

1. exec不等於console命令

2. exec的輸入輸出流須要本身處理

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

4. 注意權限問題

相關文章
相關標籤/搜索