2011-10-16 61 views
2

请原谅我,我不是Linux核心程序员。这是我第一次做任何Linux编码,因此对我一无所知。在Android应用程序中执行shell脚本

因此,我已经阅读了大量关于这个主题的文章,并且我很难弄清楚我的代码正在发生什么。基本上,我试图创建一个个人档案应用程序。该设备已生根并包含BusyBox。我写了一个linux脚本,根据登录的用户交换/ data和/ cache分区。

当我从ADB执行这个脚本时,它完美地工作。我想在应用中实现它会相当容易。

#SP登录用户名密码

Android的重新初始化与新的配置文件和一切都很好。这是我在Android的:

Log.v("Profiles", "sp login " + user + " " + password); 
Process process = Runtime.getRuntime().exec("sp login " + user + " " + password); 

BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 
int read; 
char[] buffer = new char[4096]; 
StringBuffer output = new StringBuffer(); 
while ((read = reader.read(buffer)) > 0) { 
    output.append(buffer, 0, read); 
} 
reader.close(); 
process.waitFor(); 
Log.v("Profiles", output.toString()); 

唯一的记录是我的“回声”在实际的脚本本身。我看不到在该脚本中执行的命令的任何结果。例如,当在ADB中运行时,所有安装命令和我所做的不同事情都有输出。这些都不会在输出字符串中输出。

有什么建议吗?

+0

如果'password'包含shell元字符,如';'或'&'或'*'或'''你执行exec()'调用可能不执行,你?期望。如果Android允许你访问更像'execve(2)'而不像'system(3)'的东西,那么使用它会是明智的。 (虽然我不认为这与你目前的问题有关。) – sarnold

+0

没有。密码中没有特殊字符。只是一个简单的字符串,虽然这是我需要检查的东西。而且,尽管我对这方面的知识并不是很了解,但Android似乎并不存在。 – normmcgarry

回答

0

您需要为进程执行“su”,它将执行您的shell脚本。

否则,即使设备已经生根,该过程也没有root权限。

下面的代码是一个供您参考的例子。

public void RunAsRoot(String[] cmds){ 
    try{ 
     Process p = Runtime.getRuntime().exec("su"); 
     DataOutputStream os = new DataOutputStream(p.getOutputStream()); 
     for(String tmpCmds : cmds){ 
      os.writeBytes(tmpCmds+"\n"); 
      os.flush(); 
      os.writeBytes("exit\n"); 
      os.flush(); 
     } 
     BufferedReader stdInput = new BufferedReader(new 
      InputStreamReader(p.getInputStream())); 

     // read the output from the command 
     String s = null; 
     while ((s = stdInput.readLine()) != null) { 
      System.out.println(s); 
     } 
    }catch(Exception e){ 
     Log.e(LOG_TAG, "RunAsRoot exec failed"); 
    } 

}