How can we execute a shell script file from my Android Application

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

Please Tell me it is possible to run a shell script file from My Android application.

and read the data from script file.

If it is possible than how to proceed , Please give me some guideline.

回答1:

You can use this code snippet (from Aaron C)

void execCommandLine(String command)     {         Runtime runtime = Runtime.getRuntime();         Process proc = null;         OutputStreamWriter osw = null;          try         {             proc = runtime.exec("su");             osw = new OutputStreamWriter(proc.getOutputStream());             osw.write(command);             osw.flush();             osw.close();         }         catch (IOException ex)         {             Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);             return;         }         finally         {             if (osw != null)             {                 try                 {                     osw.close();                 }                 catch (IOException e){}             }         }          try          {             proc.waitFor();         }         catch (InterruptedException e){}          if (proc.exitValue() != 0)         {             Log.e("execCommandLine()", "Command returned error: " + command + "\n  Exit code: " + proc.exitValue());         }     } 

But this requires root access I think.

You could also try to use GScript



回答2:

I've been using this to run shell scripts in my android app. Only thing I've yet to figure out how to do is direct the output to where I want it. You don't need root for this, which is why I'm posting.

 Process process = Runtime.getRuntime().exec("top -n 1");  //Get the output of top so that it can be read  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); 


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