Android Runtime使得直接調用底層Linux下的可執行程式或指令碼成為可能
比如Linux下寫個測試載入器,直接編譯後apk中通過Runtime來調用
或者寫個指令碼,apk中直接調用,省去中介層或者JNI
這個至少效率應該比較高吧
代碼:
public class test extends Activity {<br />TextView text;</p><p> /** Called when the activity is first created. */<br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);</p><p> text = (TextView) findViewById(R.id.text);</p><p> Button btn_ls = (Button) findViewById(R.id.btn_ls);<br /> btn_ls.setOnClickListener(new OnClickListener() {<br />public void onClick(View v) {<br />do_exec("ls /mnt/sdcard");<br />}<br /> });<br /> Button btn_cat = (Button) findViewById(R.id.btn_cat);<br /> btn_cat.setOnClickListener(new OnClickListener() {<br />public void onClick(View v) {<br />do_exec("cat /proc/version");<br />}<br /> });<br /> Button btn_rm = (Button) findViewById(R.id.btn_rm);<br /> btn_rm.setOnClickListener(new OnClickListener() {<br />public void onClick(View v) {<br />do_exec("rm /mnt/sdcard/1.jpg");<br />}<br /> });<br /> Button btn_sh = (Button) findViewById(R.id.btn_sh);<br /> btn_sh.setOnClickListener(new OnClickListener() {<br />public void onClick(View v) {<br />do_exec("/system/bin/sh /mnt/sdcard/test.sh 123");<br />}<br /> });<br /> }</p><p> String do_exec(String cmd) {<br /> String s = "/n";<br /> try {<br />Process p = Runtime.getRuntime().exec(cmd);<br />BufferedReader in = new BufferedReader(<br />new InputStreamReader(p.getInputStream()));<br />String line = null;<br />while ((line = in.readLine()) != null) {<br />s += line + "/n";<br />}<br />} catch (IOException e) {<br />// TODO Auto-generated catch block<br />e.printStackTrace();<br />}<br /> text.setText(s);<br />return cmd;<br /> }<br />}
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