【问题标题】:Execute multiple root shell commands in Android在 Android 中执行多个 root shell 命令
【发布时间】:2014-11-09 20:10:14
【问题描述】:

我正在开发一个在不同时间执行多个 shell 命令的应用程序。 我正在使用以下方法:

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

此方法工作正常,但每次我需要调用它时它总是打开一个新外壳,因此它显示烦人的吐司“应用程序已被授予 root 权限”。 我认为这是因为它总是打开和关闭具有 SU 访问权限的新外壳。我的问题是:有没有办法让 SU shell 始终打开,以便我可以在需要时运行我的命令而不会收到 SU toast?

【问题讨论】:

标签: android root


【解决方案1】:

所以这可能有点晚了,但如果您仍在寻找解决方案:只需声明

private Process p = Runtime.getRuntime().exec("su");

在您的班级中全球范围内。这应该符合您的需求。 实际上,您可以在 onResume() 和 destroy() 中再次在 onPause() 中生成该进程。

@Override  
onResume() {
  if(//check for root) {
     try { 
         this.p = Runtime.getRuntime().exec("su"); 
         } 
     catch(IOException e) { 
         // Exception handling goes here 
         }
     }
  //set up everything else
}

@Override  
onPause() {
  this.p.destroy();
}

顺便说一句:我在上述方法中看到了严重的内存泄漏:您打开了各种 SU 进程,但再也没有destroy()它们。根据您调用此方法的频率,在您的应用关闭之前,RAM 中将会有越来越多的 SU 进程。

所以

public void runAsRoot(String[] cmds){ try { Process p = Runtime.getRuntime().exec("su"); } catch(IOException e) { // Exception handling goes here } DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) { os.writeBytes(tmpCmd+"\n"); }
os.writeBytes("exit\n"); os.flush(); p.destroy(); }

在这里会很好。我也在问自己是否可以编译你的方法。通常Runtime.getRuntime().exec(); 必须被try/catch 包围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2015-11-20
    相关资源
    最近更新 更多