-2

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.

TheWanderer
  • 16,775
  • 6
  • 49
  • 63
  • Possible duplicate of [Determine if running on a rooted device](https://stackoverflow.com/questions/1101380/determine-if-running-on-a-rooted-device) – Dave S Sep 12 '18 at 21:44

2 Answers2

3

You can consider to use RootBeer. It It uses various checks to indicate whether device is rooted or not.

As simple as

RootBeer rootBeer = new RootBeer(context);
if(rootBeer.isRooted()){

}
Fernando Tan
  • 634
  • 4
  • 14
  • Thanks, but I'm more interested in knowing whether or not what I've made is actually a good solution. Looking at the source of that, it looks like it also does the common checks for existing SU binaries, root apps, etc, which can all give false positives. My app is looking for root to use it or use a non-root alternative. – TheWanderer May 04 '17 at 01:58
0

So I actually found that isn't a reliable method, namely because stackTrace is never null. Changing

return stackTrace == null;

to

return stackTrace[0] == null;

makes it work.

TheWanderer
  • 16,775
  • 6
  • 49
  • 63