Android runtime makes it possible to directly invoke executable programs or scripts under the underlying Linux
For example, write a test tool in Linux, directly compiled after the APK in the runtime to invoke
or write a script that calls directly from the APK, eliminating the middle or jni
At least the efficiency should be higher.
Code:
[Java]View Plaincopy
-
1 Public classTest extends Activity {2 TextView text; 3 4 /** Called when the activity is first created.*/ 5 @Override6 Public voidonCreate (Bundle savedinstancestate) {7 super.oncreate (savedinstancestate); 8 Setcontentview (R.layout.main); 9 TenText =(TextView) Findviewbyid (R.id.text); One AButton Btn_ls =(Button) Findviewbyid (R.id.btn_ls); -Btn_ls.setonclicklistener (NewOnclicklistener () { - Public voidOnClick (View v) { theDo_exec ("Ls/mnt/sdcard"); - } - }); -Button Btn_cat =(Button) Findviewbyid (R.ID.BTN_CAT); +Btn_cat.setonclicklistener (NewOnclicklistener () { - Public voidOnClick (View v) { +Do_exec ("cat/proc/version"); A } at }); -Button BTN_RM =(Button) Findviewbyid (R.ID.BTN_RM); -Btn_rm.setonclicklistener (NewOnclicklistener () { - Public voidOnClick (View v) { -Do_exec ("rm/mnt/sdcard/1.jpg"); - } in }); -Button Btn_sh =(Button) Findviewbyid (R.ID.BTN_SH); toBtn_sh.setonclicklistener (NewOnclicklistener () { + Public voidOnClick (View v) { -Do_exec ("/system/bin/sh/mnt/sdcard/test.sh 123"); the } * }); $ } Panax Notoginseng - string do_exec (string cmd) { theString s ="/ N"; + Try { AProcess p =runtime.getruntime (). exec (CMD); theBufferedReaderinch=NewBufferedReader ( + NewInputStreamReader (P.getinputstream ())); -String line =NULL; $ while(line =inch. ReadLine ())! =NULL) { $s + = line +"/ N"; - } -}Catch(IOException e) { the //TODO auto-generated Catch block - E.printstacktrace (); Wuyi } the Text.settext (s); - returncmd; Wu } - } About
Test.sh:
Echo test.sh
echo $
Need to note:
1. exec does not equal the console command
2. exec's input/output stream needs to be handled by itself
3. Exec execution blocking, non-blocking, returning result problems
4. Attention to permissions issues
There is an article about the more in-depth, paste out research:
Http://blog.csdn.net/zmyde2010/archive/2011/01/12/6130895.aspx
http://kuangbaoxu.javaeye.com/blog/210291
Android: Via Runtime.getruntime (). Exec calls programs or scripts under the underlying Linux