需求:App 需要 Root 權限執行特定命令(如修改系統文件、掛載分區)。
which su 或嘗試執行 su -c "id"。Process process = Runtime.getRuntime().exec("su");DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes("command\n"); os.writeBytes("exit\n"); os.flush();InputStream is = process.getInputStream(); 異步讀取防死鎖。process.waitFor(); 獲取退出碼。public class RootUtil {
public static boolean exec(String... commands) {
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
for (String cmd : commands) {
os.writeBytes(cmd + "\n");
}
os.writeBytes("exit\n");
os.flush();
int result = process.waitFor();
return result == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
// 調用
RootUtil.exec("mount -o remount,rw /system", "cp /sdcard/file /system/app/");
| 問題 | 解決 |
|---|---|
| 寫命令後不寫 exit | Shell 不退出,waitFor() 永久阻塞 |
| 不異步讀取輸出流 | 管道滿導致死鎖,用線程讀取或 ProcessBuilder.redirectErrorStream(true) |
| 假設所有設備 su 路徑相同 | 用 which su 動態獲取或嘗試常見路徑 /system/bin/su /system/xbin/su |
| 無 Root 時崩潰 | 捕獲 IOException,返回 false 提示用戶 |