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
Public class Test extends Activity {
TextView text;
/** Called when the activity is first created. * /
@Override
Public void onCreate (Bundle savedinstancestate) {
Super. OnCreate (savedinstancestate);
Setcontentview (R.layout.main);
Text = (TextView) Findviewbyid (R.id.text);
Button Btn_ls = (button) Findviewbyid (R.id.btn_ls);
Btn_ls.setonclicklistener (new Onclicklistener () {
Public void OnClick (View v) {
Do_exec ("Ls/mnt/sdcard");
}
});
Button Btn_cat = (button) Findviewbyid (R.ID.BTN_CAT);
Btn_cat.setonclicklistener (new Onclicklistener () {
Public void OnClick (View v) {
Do_exec ("cat/proc/version");
}
});
Button Btn_rm = (button) Findviewbyid (R.ID.BTN_RM);
Btn_rm.setonclicklistener (new Onclicklistener () {
Public void OnClick (View v) {
Do_exec ("rm/mnt/sdcard/1.jpg");
}
});
Button Btn_sh = (button) Findviewbyid (R.ID.BTN_SH);
Btn_sh.setonclicklistener (new Onclicklistener () {
Public void OnClick (View v) {
Do_exec ("/system/bin/sh/mnt/sdcard/test.sh 123");
}
});
}
String do_exec (string cmd) {
String s = "/n";
Try {
Process p = runtime.getruntime (). exec (CMD);
BufferedReader in = new BufferedReader (
New InputStreamReader (P.getinputstream ()));
String line = null;
while (line = In.readline ()) = null) {
s + = line + "/n";
}
} catch (IOException e) {
//TODO auto-generated catch block
E.printstacktrace ();
}
Text.settext (s);
return cmd;
}
}
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
by Runtime.getruntime (). Exec calls programs or scripts under the underlying Linux