How do you run a shell script inside of an Android app?

前端 未结 1 817
失恋的感觉
失恋的感觉 2021-02-03 15:28

I am trying to write an android app for root users that runs a series of shell commands, or a shell script if that is preferable, and displays the output... can anyone point me

相关标签:
1条回答
  • 2021-02-03 15:53

    This snippet requires root access, but will execute the given String as a shell command

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题