Syntax for shell command in Android app

你说的曾经没有我的故事 提交于 2019-12-04 19:12:40
restInPieces

SOLUTION FOUND! Thanks to the link suggested by onit here. See the code below: for superuser shell commands to work properly, you first need to create a superuser shell and assign it to a process, then write and read on it's input and output streams respectively.

Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
//from here all commands are executed with su permissions
stdin.writeBytes("ls /data\n"); // \n executes the command
InputStream stdout = p.getInputStream();
byte[] buffer = new byte[BUFF_LEN];
int read;
String out = new String();
//read method will wait forever if there is nothing in the stream
//so we need to read it in another way than while((read=stdout.read(buffer))>0)
while(true){
    read = stdout.read(buffer);
    out += new String(buffer, 0, read);
    if(read<BUFF_LEN){
        //we have read everything
        break;
    }
}
//do something with the output
user2710689

Use the function below:

public void shellCommandRunAsRoot(String Command)
{
 try 
  {
     Process RunProcess= Runtime.getRuntime().exec("su");
     DataOutputStream os;
     os = new DataOutputStream(RunProcess.getOutputStream()); 

     os.writeBytes(cmds+"\n");
         os.writeBytes("exit+\n");
     os.flush();

  }
  catch (IOException e)
  {
     // Handle Exception 
  }    
}

Usage:

shellCommandRunAsRoot("pkill firefox");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!