Android: Requesting root access in your app
This snippet shows how root access can be requested inside an application in order to write a file into a place we do not have permission to access usually. Requesting root access will only work if your phone allows it, or it has been ‘rooted’ (hacked to allow superuser permissions).
Process p;
try {
// Preform su to get root privledges
p = Runtime.getRuntime().exec("su");
// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("echo \"Do I have root?\" >/system/sd/temporary.txt\n");
// Close the terminal
os.writeBytes("exit\n");
os.flush();
try {
p.waitFor();
if (p.exitValue() != 255) {
// TODO Code to run on success
toastMessage("root");
}
else {
// TODO Code to run on unsuccessful
toastMessage("not root");
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
toastMessage("not root");
}
} catch (IOException e) {
// TODO Code to run in input/output exception
toastMessage("not root");
}
Where my “toastMessage” is just a function which creates a toast to display on the screen. On phones with superuser permissions installed (root access) this will display a dialog asking the user to allow or deny the application permission to have root access:
Ref
anddev.org





This was a great help, I appreciate this post!
hi~!
‘root access dialog’ is made by you?
or, made by android system?
if app requires root permissions
then automatically show up ‘root access dialog’?
IOException raised when write a file into a place we do not have permission(ex : /system/sd/)
and app finished..
not show ‘root access dialog’
i want make app writing a file into /system/
help me..
The root access dialog is part of the android system, but its is only avaliable if you have “rooted” the phone it is running on otherwise permission is simply denied.
Thanks,
‘rooted’ gets using shell command ‘mount’ ?
No, I think your getting confused. Mount has nothing to do with this.
A routed phone is one that has been hacked to allow root access. Your application will only work on phones that have been rooted by the user. This is obvious for security reasons.
How can I use this to access another applications database?