Android 程式以 Java 開發,接上除錯器執行 adb shell 就能下 Linux 命令;而在 App 內部要拿到命令的輸出,就得靠 Runtime 與串流處理。以下示範一組可重複使用的實作。

設計上拆成兩個類別:CommandHelper 負責執行命令並控管逾時,CommandResult 負責承載回傳結果。
package com.example.task_aidl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CommandHelper {
// 預設逾時(毫秒)
public static int DEFAULT_TIMEOUT;
public static final int DEFAULT_INTERVAL = 1000;
public static long START;
public static CommandResult exec(String command) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(command); // 建立子進程
CommandResult commandResult = wait(process);
if (process != null) {
process.destroy();
}
return commandResult;
}
private static boolean isOverTime() {
return System.currentTimeMillis() - START >= DEFAULT_TIMEOUT;
}
private static CommandResult wait(Process process) throws InterruptedException, IOException {
BufferedReader errorStreamReader = null;
BufferedReader inputStreamReader = null;
try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
START = System.currentTimeMillis();
boolean isFinished = false;
for (;;) {
if (isOverTime()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}
if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor()); // 等命令執行完再往下走
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = errorStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setError(buffer.toString());
}
if (inputStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inputStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setOutput(buffer.toString());
}
return result;
}
try {
isFinished = true;
process.exitValue();
} catch (IllegalThreadStateException e) {
// 進程尚未結束
isFinished = false;
Thread.sleep(DEFAULT_INTERVAL);
}
}
} finally {
if (errorStreamReader != null) {
try { errorStreamReader.close(); } catch (IOException e) { }
}
if (inputStreamReader != null) {
try { inputStreamReader.close(); } catch (IOException e) { }
}
}
}
}
package com.example.task_aidl;
public class CommandResult {
public static final int EXIT_VALUE_TIMEOUT = -1;
private String output;
void setOutput(String error) { output = error; }
String getOutput() { return output; }
int exitValue;
void setExitValue(int value) { exitValue = value; }
int getExitValue() { return exitValue; }
private String error;
public String getError() { return error; }
public void setError(String error) { this.error = error; }
}
@Override
public String killProc(String PID) throws RemoteException {
String cmd = "kill -9 " + PID;
String reply = "";
Log.v("cmd", cmd);
try {
CommandHelper.DEFAULT_TIMEOUT = 5000;
CommandResult result = CommandHelper.exec(cmd);
if (result != null) {
if (result.getError() != null) {
Log.v("Output", "Error:" + result.getError());
reply = result.getError();
}
if (result.getOutput() != null) {
Log.v("Output", "Output:" + result.getOutput());
reply = result.getOutput();
}
}
} catch (IOException ex) {
Log.v("Output", "IOException:" + ex.getLocalizedMessage());
} catch (InterruptedException ex) {
Log.v("Output", "InterruptedException:" + ex.getLocalizedMessage());
}
return reply;
}
這套寫法的關鍵在於逾時控制:透過輪詢 process.exitValue() 並捕捉 IllegalThreadStateException 判斷進程是否仍在跑,避免命令卡死時把主流程一起拖住。若要在已 root 的裝置上執行需要特權的命令,把 exec 中的命令字串改為 su -c "..." 形式即可。