How to run root commands from Android application?

2019-09-21 16:56发布

问题:

I want to write an application which roots the device on which it is installed, I mean by installing this app you will be able to root your device without a computer, just like the app in the following link,

http://www.kingoapp.com/root-tutorials/how-to-root-android-without-computer.htm

I've searched a lot on how to do that using Java code for Android devices, but there was no clear solution to me. Based on my research, I think we need the following steps:

1- Being able to use shell commands in Android using Runtime.getRuntime().exec();

2- Executing a command that gains root privileges (I think su, but this needs a rooted device to be executed).

3- Initiate a root command that will root the device.

I couldn't find a code explanation on how to do the steps above. I want to understand this process first, the commands that can be used in it, then I want to try to implement it by myself. Since there are many apps on the store that offer this feature, then implementing it must be feasible.

Could anyone please explain to me how to implement this process?

Also, is there a possibility to write a code for the opposite process, which is unrooting the device?

Any help is appreciated.

Thanks.

回答1:

To run root commands, you have to use the following format:

public void RunAsRoot(String[] cmds){
    Process p = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(p.getOutputStream());            
    for (String tmpCmd : cmds) {
        os.writeBytes(tmpCmd+"\n");
    }           
    os.writeBytes("exit\n");  
    os.flush();
}

where you pass in an array of strings, each string being a command that needs to be executed. For example:

String[] cmds = {"sysrw", "rm /data/local/bootanimation.zip", "sysro"};