开发者社区 问答 正文

确定是否在有根设备上运行

我的应用程序具有某些功能,这些功能只能在具有root用户权限的设备上运行。与其让该功能在使用时失败(然后向用户显示适当的错误消息),不如让我先静默检查root是否可用,如果没有,首先隐藏相应的选项。 。

有没有办法做到这一点?

展开
收起
Puppet 2020-01-20 09:09:07 373 分享 版权
1 条回答
写回答
取消 提交回答
  • 这是一个将检查根的三种方法之一。

    /** @author Kevin Kowalewski */
    public class RootUtil {
        public static boolean isDeviceRooted() {
            return checkRootMethod1() || checkRootMethod2() || checkRootMethod3();
        }
    
        private static boolean checkRootMethod1() {
            String buildTags = android.os.Build.TAGS;
            return buildTags != null && buildTags.contains("test-keys");
        }
    
        private static boolean checkRootMethod2() {
            String[] paths = { "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
                    "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
            for (String path : paths) {
                if (new File(path).exists()) return true;
            }
            return false;
        }
    
        private static boolean checkRootMethod3() {
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(new String[] { "/system/xbin/which", "su" });
                BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
                if (in.readLine() != null) return true;
                return false;
            } catch (Throwable t) {
                return false;
            } finally {
                if (process != null) process.destroy();
            }
        }
    }
    
    2020-01-20 09:09:26
    赞同 展开评论
问答地址: