Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Running Shell commands though java code on Android?

I've got an app that's supposed to use some shell commands to copy a file from the sdcard to /system/media/. It will require root, and I am testing on a rooted device. I'm using runtimes to execute the shell commands, but it's not working. Here's what I've got for my runtimes

public void RunAsRoot{String[] commands = {"sysrw", "rm /data/local/bootanimation.zip", "sysro"};{
    Process p = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(p.getOutputStream());            
    for (String tmpCmd : commands) {
    os.writeBytes(tmpCmd+"
");
    }           
    os.writeBytes("exit
");  
    os.flush();
}

But my logcat only shows two of them not getting rejected

07-30 03:14:11.112: WARN/su(3593): request rejected (10047->0 /system/bin/sh)
07-30 03:14:11.132: DEBUG/su(3592): 10047 com.bba.stormdroid executing 0 /system/bin/sh using shell /system/bin/sh : sh
07-30 03:14:11.152: WARN/su(3594): request rejected (0->0 /system/bin/sh)
07-30 03:14:11.182: WARN/su(3595): request rejected (0->0 /system/bin/sh)
07-30 03:14:11.202: WARN/su(3596): request rejected (0->0 /system/bin/sh)
07-30 03:14:11.242: DEBUG/su(3597): 10047 com.bba.stormdroid executing 0 /system/bin/sh using shell /system/bin/sh : sh

Those two look to be the sysrw and sysro commands, yet the app still asks for root permission when I trigger this code. I'm new to working with root stuff and I can't seem to figure out how to get this to work.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

To run root commands, you have to use the flllowing 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[] commands = {"sysrw", "rm /data/local/bootanimation.zip", "sysro"};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...