I'm developing my first Android
application, and I'm curious if there are any "standard" ways for executing privileged shell
commands. I've only been able to find one way to do it, by executing su
, and then appending my commands to stdin
of the su
process.
DataOutputStream pOut = new DataOutputStream(p.getOutputStream());
DataInputStream pIn = new DataInputStream(p.getInputStream());
String rv = "";
// su must exit before its output can be read
pOut.writeBytes(cmd + "\nexit\n");
pOut.flush();
p.waitFor();
while (pIn.available() > 0)
rv += pIn.readLine() + "\n";
I've read about wrapping privileged (superuser
) calls up in JNI
: is this possible? If so, how would one go about accomplishing it? Other than that, are there any other ways of calling privileged instructions from Java
?
A possible solution I know is to sign your application as system, which is not exactly the same as root as far as I know: How to sign Android app with system signature?. But I suppose this is not what you wanted.
Another thing I did is to create a native application that does what is needed, running it as an external process. But it is necessary to give this native application the privileges you need and the suid bit, provided the partition is not nosuid. But this is not what you needed either I suppose.
C code called through JNI should be subject to the same limitations as living in the same process, I suppose.
If you have the su binary available then you can run commands from java with something like:
Runtime.getRuntime().exec("su -c reboot")
.I don't remember any other way.
As far as I know, you can only run command-line commands using root privileges. You can use this generic class I made that wraps the root access in your code: http://muzikant-android.blogspot.com/2011/02/how-to-get-root-access-and-execute.html
All you need to do is extend this class and override the
getCommandsToExecute
method to return the commands you want to execute as root.