简体   繁体   English

如何通过su执行shell命令?

[英]How to execute shell commands through su?

I tried following way but its not working for me : 我尝试了以下方法,但对我不起作用:

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

I tried this as well : 我也尝试过这个:

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

But none of the above method is working. 但是上述方法均无效。 However following command is working for me in shell through adb : 但是以下命令通过adb在shell中为我工作:

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

So I even tried this : 所以我什至尝试了这个:

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

But even this didn't work. 但是,即使这样也不起作用。 Can anyone please help me!!!! 谁能帮帮我吗!!!!

I use an OutputStream instead of a DataOutputStream 我使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM