标签:
Android Runtime使得直接调用底层Linux下的可执行程序或脚本成为可能
比如Linux下写个测试工具,直接编译后apk中通过Runtime来调用
或者写个脚本,apk中直接调用,省去中间层或者JNI
这个至少效率应该比较高吧
代码:
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下的程序或脚本
标签:
原文地址:http://www.cnblogs.com/rosepotato/p/5566803.html