在開發過程當中會有需要root權限,之前一直感覺很深奧。直到有一天。。。
首先考慮了一種最直接的方法,通過命令行來獲取root權限。我們可以通過adb shell來獲取su權限,作爲應用同樣應該也可以通過命令行來獲取。
附上代碼:
public boolean getRootPermission(String pkgCodePath) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
String chmod = "chmod 777 " + pkgCodePath;
os.writeBytes(chmod + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return true;
}
下面實驗一下是否真的獲取到了目錄的root權限:
我們來查看一下/proc文件夾裏的內容
private void listData() {
try {
Process p = Runtime.getRuntime().exec("ls /proc");
Readline readline = new Readline();
tv_result.setText(readline.readline(p));
} catch (IOException e) {
e.printStackTrace();
}
}
可以獲取到。
更多root相關實踐仍在研究中。