Syntax for shell command in Android app

2019-04-14 23:33发布

问题:

I am trying to run

String command = "su -c 'busybox ls /data'";
p = Runtime.getRuntime().exec(command);

in my app, but it seems like the syntax is somehow wrong. I have no problem running it from the terminal emulator app on the phone, though, so I just can't understand why it is not working when called from within my app.

Any help is deeply appreciated!

回答1:

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


回答2:

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");