此所谓三种方式,只是个人认为。本人还是菜鸟初涉,所以有所错误,请指正。
个人认为,Java调用外部命令。无非三种情况:
一.是只执行命令,不考虑返回值。
二.是执行命令的同时,还需要得到返回值。
三.是执行命令的同时,等待得到返回值。
二和三的不同在于,前者之间可以得到返回。后者通过某些情况后才可以得到返回。
(一)
Runtime.getRuntime().exec("su");
(二)
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd1 + "\n");
os.writeBytes("exit\n");
os.flush();
process.getErrorStream().close();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1) {
result = result + new String(re);
}
Log.i(TAG, "result = " + result);
in.close();
process.waitFor();
my = new Thread() {
public void run() {
Process process = null;
DataOutputStream os = null;
String result = "";
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes("getevent /dev/input/event3" + "\n");
os.flush();
os.close();
process.getErrorStream().close();
InputStream in = process.getInputStream();
byte[] re = new byte[19];
Log.i(TAG, "Thread start---");
while(true) {
if (in.read(re) != -1) {
Log.i(TAG, "load string...");
result = result + new String(re);
Log.i(TAG, "run result = " + result);
} else {
Thread.sleep(100);
Log.i(TAG, "sleep result = " + result);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
}
};