手机root是我工作后做的第一个安全功能,上网查了一下,答案蛮多,随便选了一种,结果判断过程中出现了问题。
网上所说的方法的主要原理是:当手机被root后,在 /system/app/ 文件夹下会生成一个“Superuser.apk”的应用软件。则有:
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
但是很多手机,如小米,魅族的部分手机不支持该判断。那天用红米2测试的时候发现手机明明没有root但是这个方法返回的值是true。查阅的网上的资料,原来小米系统中本身含有这个apk的,而且知道了:我们所说的 “root过了” 和“获取了root权限”并不是完全相同的概念。像小米,魅族这样的手机一般都是已经root过的,但是未必都获取了root权限,可能都是出于一种安全角度考虑的吧!
但是问题还是要解决滴!郁闷之中查到另一种方法,就是判断 android.os.Build.TAGS 字符串中是否含有"test-keys"这个字符串,效果和上述方法是一样的。最后找了一种万能的方法就是运行shell-command命令的方式判断,这种方法可以直接判断手机设备是否获取了root权限。十分管用的方法。
public class AndroidUtil {
public static boolean isDeviceRooted() {
if (checkRootMethod1()) {
return true;
}
if (checkRootMethod2()) {
return true;
}
if (checkRootMethod3()) {
return true;
}
return false;
}
public static boolean checkRootMethod1() {
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}
public static boolean checkRootMethod2() {
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
} catch (Exception e) {
}
return false;
}
public static boolean checkRootMethod3() {
if (new ExecShell().executeCommand(ExecShell.SHELL_CMD.check_su_binary) != null) {
return true;
} else {
return false;
}
}
}
public class ExecShell {
private static String LOG_TAG = ExecShell.class.getName();
public static enum SHELL_CMD {
check_su_binary(new String[] { "/system/xbin/which", "su" }), ;
String[] command;
SHELL_CMD(String[] command) {
this.command = command;
}
}
public ArrayList executeCommand(SHELL_CMD shellCmd) {
String line = null;
ArrayList fullResponse = new ArrayList();
Process localProcess = null;
try {
localProcess = Runtime.getRuntime().exec(shellCmd.command);
} catch (Exception e) {
return null;
// e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
localProcess.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(
localProcess.getInputStream()));
try {
while ((line = in.readLine()) != null) {
Log.d(LOG_TAG, "–> Line received: " + line);
fullResponse.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d(LOG_TAG, "–> Full response was: " + fullResponse);
return fullResponse;
}
}
如果返回的值不为null,说明已经获取root权限。这种方法覆盖的机型蛮全的,如果有漏洞,希望大家指出,大家一起进步!