通过Android上的Java代码运行Shell命令?

时间:2011-07-30 09:23:53

标签: java android shell exec su

我有一个应用程序应该使用一些shell命令将文件从SD卡复制到/ system / media /。它将需要root,我正在root设备上进行测试。我正在使用运行时来执行shell命令,但它不起作用。 这是我为我的运行时所获得的

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

但是我的logcat只显示其中两个没有被拒绝

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

这两个看起来是sysrw和sysro命令,但当我触发此代码时,应用程序仍然要求root权限。 我刚开始使用root的东西,我似乎无法弄清楚如何让它工作。

1 个答案:

答案 0 :(得分:26)

要运行root命令,必须使用以下格式:

    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();
}

传入一个字符串数组,每个字符串都是需要执行的命令。例如:

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