【发布时间】:2014-02-27 02:47:03
【问题描述】:
目前我有使用终端模拟器应用程序在 android 上运行的 shell 脚本命令。需要准备一个应用程序以从我的 android 应用程序调用 shell 脚本,在我的应用程序上显示 shell 脚本的结果。任何人都可以提出最好的方法来做到这一点。
【问题讨论】:
目前我有使用终端模拟器应用程序在 android 上运行的 shell 脚本命令。需要准备一个应用程序以从我的 android 应用程序调用 shell 脚本,在我的应用程序上显示 shell 脚本的结果。任何人都可以提出最好的方法来做到这一点。
【问题讨论】:
使用的代码来自here
public void runShellCommand(String[] cmds) throws Exception {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
InputStream is = p.getInputStream();
for (String temp : cmds) {
os.writeBytes(temp+"\n");
int read= 0;
byte[] buff = new byte[4096];
// if cmd requires an output
// due to the blocking behaviour of read(...)
boolean cmdRequiresAnOutput = true;
if (cmdRequiresAnOutput) {
while( is.available() <= 0) {
try { Thread.sleep(200); } catch(Exception ex) {}
}
while( is.available() > 0) {
read = is.read(buff);
if ( read <= 0 ) break;
String str = new String(buff,0,read);
console.println("#> "+str);
}
}
}
os.writeBytes("exit\n");
os.flush();
}
使用时间长的命令需要休眠。
【讨论】: