How can we execute a shell script file from my And

2019-05-23 08:07发布

问题:

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


标签: android shell