開發APP有時候會遇到想直接用shell指令的方式來執行想要的程式,而不想為了一個功能寫了一堆Java code
透過程式執行shell指令有兩中方式,一種是只要執行,不管執行結果的回覆內容比較簡單,如下:
try {
Runtime.getRuntime().exec("you shell command");
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
另外一種就是想知道下完指令的回傳結果
private static void runShellCommand(String command) {
Process process = null;
BufferedReader bufferedReader = null;
StringBuilder mShellCommandSB =new StringBuilder();
Log.d(TAG, "runShellCommand :" + command);
mShellCommandSB.delete(0, mShellCommandSB.length());
String[] cmd = new String[] { "/system/bin/sh", "-c", command };
try {
byte b[] = new byte[1024];
process = Runtime.getRuntime().exec(cmd);
bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
mShellCommandSB.append(line);
}
Log.d(TAG, "runShellCommand result : " + mShellCommandSB.toString());
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO: handle exception
}
}
if (process != null) {
process.destroy();
}
}
}
Place your comment