I'm making an app that needs to check for root access. I found some solutions here on StackOverflow, but they involved checking hard paths for known root binaries, which isn't really all that universal, so I wanted to avoid using that.
At first, I made a new Process to execute su
, then checked its InputStream for strings like "not found" or "permission denied." I thought that worked, until I tried it on an Android 4.1 emulator, where the InputStream is completely different from the StackTrace returned in an exception.
After a while, I came up with this function:
private boolean testSudo() {
StackTraceElement[] stackTrace = new StackTraceElement[] { null };
try{
Runtime.getRuntime().exec("su");
} catch (Exception e) {
stackTrace = e.getStackTrace();
}
return stackTrace == null;
}
What I'm wondering is, is this actually a reliable method? In theory, it returns true when the StackTrace remains null, but returns false if something has been added to it. To me, it looks universal, but so did my old method.
EDIT: this doesn't answer my question. I'm not asking how to check for root, but rather if my method is accurate, or if there are any glaring flaws.