Android run bash command in app

前端 未结 1 1485
自闭症患者
自闭症患者 2020-12-16 05:52

Hi i\'m developing an application which requires me to run some bash code is there a way i can hard code the script into my app and then run it? For instance (this is a VERY

相关标签:
1条回答
  • 2020-12-16 06:17

    If I understand you correctly, all you have to do is change the one line example method to something which accepts and sends multiple lines, like so:

        public Boolean execCommands(String... command) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process process = rt.exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
    
            for(int i = 0; i < command.length; i++) {
                os.writeBytes(command[i] + "\n");
                os.flush();
            }
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (IOException e) {
            return false;
        } catch (InterruptedException e) {
            return false;
        }
        return true; 
    }
    

    That way, you can call your multiline bash commands like so:

        String[] commands = {
                "echo 'test' >> /sdcard/test1.txt",
                "echo 'test2' >>/sdcard/test1.txt"
        };
    
        execCommands(commands);
    
        String commandText = "echo 'foo' >> /sdcard/foo.txt\necho 'bar' >> /sdcard/foo.txt";
    
        execCommands(commandText.split("\n"));
    
    0 讨论(0)
提交回复
热议问题