使用linux命令首先要獲得root,執行命令時記得加上 busybox 。一般我們在用java IO的基本方法不能把檔案放到usb檔案,可以用linux命令來做。
ProcessBuilder pb = new ProcessBuilder("/system/bin/sh");
//java.lang.ProcessBuilder: Creates operating system processes.
pb.directory(new File("/"));//設定shell的目前的目錄。
try {
Process proc = pb.start();
//擷取輸入資料流,可以通過它擷取SHELL的輸出。
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
//擷取輸出資料流,可以通過它向SHELL發送命令。
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc
.getOutputStream())), true);
out.println("pwd");
out.println("su root");//執行這一句時會彈出對話方塊(以下程式要求授予最高許可權...),要求使用者確認。
out.println("cd /data/data");//這個目錄在系統中要求有root許可權才可以訪問的。
out.println("ls -l");//這個命令如果能列出當前安裝的APK的資料檔案存放目錄,就說明我們有了ROOT許可權。
out.println("exit");
// proc.waitFor();
String line;
while ((line = in.readLine()) != null) {
System.out.println(line); // 列印輸出結果
}
while ((line = err.readLine()) != null) {
System.out.println(line); // 列印錯誤輸出結果
}
in.close();
out.close();
proc.destroy();
} catch (Exception e) {
System.out.println("exception:" + e);
}
File superuser = new File("/system/bin/superuser");
if (superuser.exists())
{
// return device to original state
Process process = Runtime.getRuntime().exec("superuser");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
os.writeBytes("mount -oremount,rw /dev/block/mtdblock3 /system\n");
os.writeBytes("busybox cp /system/bin/superuser /system/bin/su\n");
os.writeBytes("busybox chown 0:0 /system/bin/su\n");
os.writeBytes("chmod 4755 /system/bin/su\n");
os.writeBytes("rm /system/bin/superuser\n");
os.writeBytes("exit\n");
os.flush();
}