开发者

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

开发者 https://www.devze.com 2023-02-09 00:52 出处:网络
Please Tell me it is possible to run a shell scrip开发者_如何学JAVAt file from My Android application.

Please Tell me it is possible to run a shell scrip开发者_如何学JAVAt 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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消