要在android应用程序中使用root权限,那么运行程序的设备必须具有root权限。
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command+"\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.d(TAG, "the device is not rooted, error message: " + e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
if(process != null) {
process.destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
如果设备获取了root权限,那么程序执行su命令时,就会提示用户进行授权,如图:
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command+"\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.d(TAG, "the device is not rooted, error message: " + e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
if(process != null) {
process.destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
如果设备获取了root权限,那么程序执行su命令时,就会提示用户进行授权,如图:
点击允许,那么我们的应用程序就得到了root权限,可以继续往下执行。
前提:真机必须有root权限才能运行此方法,也就是你的机器要经过root破解才行。经过root破解后才会有su命令,我们就是通过su命令来获得管理员权限运行我们的程序的。
转载于:https://blog.51cto.com/lovely1133/567329