Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

linux - How to run root commands from Android application?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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+"
");
    }           
    os.writeBytes("exit
");  
    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"};


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...