I have been trying many things but I still cannot find a proper way to check if my app has root access. This is what I've tried:
private boolean isRootGranted() {
Process p;
BufferedReader reader = null;
String line;
try {
p = Runtime.getRuntime().exec("su");
reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while( (line = reader.readLine()) != null) {
System.out.println(line);
}
int result;
try {
result = p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(this, "You need to grant root access", Toast.LENGTH_SHORT).show();
return false;
}
if(result != 0) {
Toast.makeText(this, "You need to grant root access", Toast.LENGTH_SHORT).show();
return false;
}
return true;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Your device is not rooted", Toast.LENGTH_SHORT).show();
return false;
} finally {
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Above code works perfectly if the device doesn't have root or the root is denied. However, every time the root is granted, it got stuck on the while loop. If I remove the while loop, it got stuck on p.waitFor()
EDIT I find out that su
command doesn't produce any output. But I don't know why it still stuck on waitFor() if no output/error produces.