本文主要记录下android 中检测设备是否root的常规方法:
- 检查系统目录:在root过的设备上,系统目录下会存在一些特殊的文件或目录,如"/system/bin/su"、"/system/xbin/su"等。可以通过检查这些文件或目录是否存在来判断设备是否已经root。
- 通过执行su命令.
package com.test.detection;
import java.io.DataOutputStream;
import java.io.File;
/**
-
@Author: zh
-
@Time: 23-11-28.
-
@Email:
-
@Describe:检测是否root
*/
public class RootUtils {public static boolean isDeviceRooted2() {
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains(“test-keys”)) {
return true;
}
File file = new File(“/system/app/Superuser.apk”);
if (file.exists()) {
return true;
}
String su = “su”;
String[] locations = {“/sbin/”, “/system/bin/”, “/system/xbin/”, “/system/sd/xbin/”, “/system/bin/failsafe/”, “/data/local/xbin/”, “/data/local/bin/”, “/data/local/”};
for (String location : locations) {
if (new File(location + su).exists()) {
return true;
}
}
return false;
}public static boolean isDeviceRooted(){
Process process = null;
try {
process = Runtime.getRuntime().exec(“su”);
DataOutputStream os = new DataOutputStream(process.getOutputStream());
os.writeBytes(“exit\n”);
os.flush();
int exitValue = process.waitFor();
return exitValue == 0;
} catch (Exception e) {
// 应用未获取root权限
} finally {
if (process != null) {
process.destroy();
}
}
return false;
}
}