如何通过su执行shell命令?

时间:2014-12-17 10:57:06

标签: java android android-shell

我尝试了以下方式,但它不适合我:

public void RunAsRoot(String cmnd){
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());                        
        os.writeBytes(cmnd +"\n");                     
        os.writeBytes("exit\n");  
        os.flush();
        p.waitFor();
}

我也尝试了这个:

public void RunAsRoot(String cmds){
        Process p = Runtime.getRuntime().exec("su -c " + cmds);
        p.waitFor();
}

但上述方法均无效。但是,以下命令通过adb在shell中工作:

 su -c "input" " keyevent" " 3"

所以我甚至试过这个:

public void RunAsRoot(String cmds){
        Process p = Runtime.getRuntime().exec("su -c \"input\" \" keyevent\" \" 3\"");
        p.waitFor();
}

但即使这样也行不通。任何人都可以帮助我!!!!

1 个答案:

答案 0 :(得分:0)

我使用OutputStream代替DataOutputStream

sh = Runtime.getRuntime().exec("su", null,null);
String now =  c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE);
Log.d(TAG, "Creating screenshot " + now +".png");
OutputStream  os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/data/local/" + now +".png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();