最近需要禁止root手机运行app,需要判断手机是否root,如果root可以弹框提示风险,也可以闪退,本文采用的方式是闪退
废话不多说贴代码
//遍历检测su是否存在
private boolean CheckRootPathSU() {
File f = null;
final String kSuSearchPaths[] = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"};
try {
for (int i = 0; i < kSuSearchPaths.length; i++) {
f = new File(kSuSearchPaths[i] + "su");
if (f != null && f.exists()) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
//常规检测su是否存在
private boolean checkRootWhichSU() {
String[] strCmd = new String[]{"/system/xbin/which", "su"};
ArrayList<String> execResult = executeCommand(strCmd);
if (execResult != null) {
return true;
} else {
return false;
}
}
大家看代码就会发现,检测手段为检测手机中是否存在su,即root需要执行su才可以获取root权限
这里采用两种方法结合的方式判断如下
public boolean isRoot() {
if (CheckRootPathSU() || checkRootWhichSU()) {
return true;
} else {
return false;
}
}
测试可以使用模拟器,楼主用的是雷电模拟器,可以模拟root,实测成功
注意,此方法可能会干掉那些曾经刷机,后来又刷稳定版的用户(此类用户root过,su会一直存在),各位根据实际业务决定
调用方式,楼主采用的方式比较严格,各位同学可以弹框提示之类,自由发挥
//判断是否root,root则闪退
if (SecurityUtil.getInstance().isRoot()){
Log.i("root","root设备准备闪退");
System.exit(0);
}
贴完整单例代码,各位同学可直接使用
public class SecurityUtil {
private SecurityUtil() {
}
public static SecurityUtil getInstance() {
return SecurityBuilder.instance;
}
private static class SecurityBuilder {
private static SecurityUtil instance = new SecurityUtil();
}
public boolean isRoot() {
if (CheckRootPathSU() || checkRootWhichSU()) {
return true;
} else {
return false;
}
}
private boolean CheckRootPathSU() {
File f = null;
final String kSuSearchPaths[] = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"};
try {
for (int i = 0; i < kSuSearchPaths.length; i++) {
f = new File(kSuSearchPaths[i] + "su");
if (f != null && f.exists()) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private boolean checkRootWhichSU() {
String[] strCmd = new String[]{"/system/xbin/which", "su"};
ArrayList<String> execResult = executeCommand(strCmd);
if (execResult != null) {
return true;
} else {
return false;
}
}
}
该博客介绍如何在Android应用中检测设备是否已被root,并在检测到root时选择闪退。通过检查系统中是否存在'su'命令来判断root状态,测试在雷电模拟器上成功。提醒这种方法可能会影响曾经刷机但现在使用稳定版的用户,具体实现可以根据业务需求调整,如弹框提示风险。

1503

被折叠的 条评论
为什么被折叠?



