RunTime执行指令
1执行单条
- Process process = Runtime.getRuntime().exec(“su”);
- Process process = Runtime.getRuntime().exec(new String[]{“su”,“logcat”});
2执行多条
public static int runCommands(String[] cmds) {
int result = -1;
if (cmds == null) {
return 0;
} else {
BufferedWriter outputStream = null;
Process process = null;
try {
process = Runtime.getRuntime().exec("su");
final Process fp = process;
outputStream = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
for (int i = 0; i < cmds.length; i++) {
try {
Log.e("OUT", cmds[i]);
outputStream.write(cmds[i] + "\n");
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
outputStream.close();
ThreadPoolUtil.getInstance().execute(() -> {
try {
BufferedReader inReader = new BufferedReader(new InputStreamReader(fp.getInputStream()));
String string = inReader.readLine();
while (string != null) {
Log.e("IN", string);
string = inReader.readLine();
}
inReader.close();
} catch (Exception e) {
e.printStackTrace();
}
});
ThreadPoolUtil.getInstance().execute(() -> {
try {
BufferedReader inReader = new BufferedReader(new InputStreamReader(fp.getErrorStream()));
String string;
while ((string = inReader.readLine()) != null) {
Log.e("ERROR", string);
}
inReader.close();
} catch (Exception e) {
e.printStackTrace();
}
});
process.waitFor();
result = process.exitValue();
Log.e("Ricardo", "exec cmds return: " + result);
} catch (Exception e) {
e.printStackTrace();
result = -1;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}