標籤:
Android Runtime使得直接調用底層Linux下的可執行程式或指令碼成為可能
比如Linux下寫個測試載入器,直接編譯後apk中通過Runtime來調用
或者寫個指令碼,apk中直接調用,省去中介層或者JNI
這個至少效率應該比較高吧
代碼:
[java] view plaincopy
1 public class test extends Activity { 2 TextView text; 3 4 /** Called when the activity is first created. */ 5 @Override 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 } 56
test.sh:
echo test.sh
echo $1
需要注意:
1. exec不等於console命令
2. exec的輸入輸出資料流需要自己處理
3. exec執行時阻塞、非阻塞,返回結果問題
4. 注意許可權問題
有個文章講的比較深入,貼出來研究:
http://blog.csdn.net/zmyde2010/archive/2011/01/12/6130895.aspx
http://kuangbaoxu.javaeye.com/blog/210291
Android: 通過Runtime.getRuntime().exec調用底層Linux下的程式或指令碼