android中通過程式碼實現檔案許可權修改
阿新 • • 發佈:2019-02-13
前提:
1.手機被root;
2.該app已經取得了root許可權。
目的:
試圖獲得系統資料夾下的檔案的讀寫許可權。
實現:
我們要使用的命令是:
chmod -R 0777 xxx/xxx等系統目錄或檔案
命令解讀:
在Unix和Linux的各種作業系統下,每個檔案(資料夾也被看作是檔案)都按讀、寫、執行設定許可權。
讀、寫、執行三項許可權可以用數字表示,就是r=4,w=2,x=1。所以,rw-r–r–用數字表示成644。
反過來說777就是rwxrwxrwx,意思是該登入使用者(可以用命令id檢視)、他所在的組和其他人都有最高許可權。
執行該命令的方法是:
Runtime.getRuntime().exec();
實現的關鍵是:
首先要通過命令”su”切換到Root身份,然後才能執行“chmod”等具體命令。
程式碼實現:
方法1:
public static boolean execCommand(String command) {
boolean status = false;
if (TextUtils.isEmpty(command)) {
return status;
}
try {
Process exec = Runtime.getRuntime().exec("su" );
OutputStream outputStream = exec.getOutputStream();
outputStream.write(command.getBytes(Charset.forName("utf-8")));
outputStream.write("\n".getBytes());
outputStream.write("exit\n".getBytes());
outputStream.flush();
int waitFor = exec.waitFor();
Log.e(TAG, "execCommand command:" +command+";waitFor=" + waitFor);
if (waitFor == 0) {
//chmod succeed
status = true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "execCommand exception=" + e.getMessage());
return false;
}
return status;
}
方法2:
public static boolean execCommand(String command) {
boolean status = false;
if (TextUtils.isEmpty(command)) {
return status;
}
String fullCommand = "su"+"\n"+command;
try {
Process exec = Runtime.getRuntime().exec(fullCommand);
int waitFor = exec.waitFor();
Log.e(TAG, "execCommand command:"+command+";waitFor=" + waitFor);
if (waitFor == 0) {
//chmod succeed
status = true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "execCommand exception=" + e.getMessage());
return false;
}
return status;
}