2012-02-21 43 views
1

命令我想在我的应用程序运行语法壳在Android应用

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

,但它似乎是语法错误莫名其妙。但是,我从手机上的终端模拟器应用程序运行它并没有问题,所以我不明白为什么在我的应用程序中调用它时无法正常工作。

任何帮助深表感谢!

+0

请问您的应用程序具有超级用户权限?应用程序权限与终端权限不同。 – onit 2012-02-21 19:08:17

+0

我的知识是有限的,但我明白,一个应用程序不能拥有超级用户权限,只有产生的进程。顺便说一句,超级用户的应用程序通知我,如果我运行说“su -c id”,并且输出是正确的,那么已经授予了root权限。你有什么建议?非常感谢 – restInPieces 2012-02-22 09:09:46

+1

不完全确定什么是错的。然而,似乎有很多其他话题在stackoverflow可能会帮助你,如果你搜索。 http://stackoverflow.com/questions/7216071/how-to-run-multiple-shell-commands-through-an-app-in-android。 http://stackoverflow.com/questions/6896618/read-command-output-inside-su-process – onit 2012-02-22 14:54:58

回答

3

解决方案找到了!感谢onithere建议的链接。请参阅下面的代码:要使超级用户shell命令正常工作,首先需要创建一个超级用户shell并将其分配给进程,然后分别对其输入和输出流进行写入和读取。

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 
+0

它不起作用! ,什么是BUFF_LEN,请仔细复印。投票 – famfamfam 2016-02-28 09:16:59

+0

@famfamfam BUFF_LEN是一个全局变量,它存储输入缓冲区的长度,没有理由downvote,因为你不知道的东西。此代码也是在几年前编写的,现在的Android API可能现在做的事情非常不同。 – restInPieces 2016-03-01 16:19:29

0

使用下面的功能:

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 
    }  
} 

用法:

shellCommandRunAsRoot("pkill firefox");