Syntax for shell command in Android app

旧街凉风 提交于 2019-12-06 13:26:45

问题


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


来源:https://stackoverflow.com/questions/9383415/syntax-for-shell-command-in-android-app

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