adb shell 을 통한 명령어 실행하기

프로그래밍/Android (Java)|2020. 11. 27. 09:41
반응형

public class MainActivity extends Activity {


    TextView tv;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        tv=(TextView)findViewById(R.id.cmdOp);

        tv.setText("Output :"+"\n"+runAsRoot());

    }


    public String runAsRoot() {


        try {

            // Executes the command.

            Process process = Runtime.getRuntime().exec("ls -l");


            // Reads stdout.

            // NOTE: You can write to stdin of the command using

            //       process.getOutputStream().

            BufferedReader reader = new BufferedReader(

                    new InputStreamReader(process.getInputStream()));


            int read;

            char[] buffer = new char[4096];

            StringBuffer output = new StringBuffer();

            while ((read = reader.read(buffer)) > 0) {

                output.append(buffer, 0, read);

            }

            reader.close();


            // Waits for the command to finish.

            process.waitFor();


            return output.toString();

        } catch (IOException e) {

            throw new RuntimeException(e);

        } catch (InterruptedException e) {

            throw new RuntimeException(e);

        }

    }

}



[출처] https://stackoverflow.com/questions/23608005/execute-shell-commands-and-get-output-in-a-textview


하지만 위와 같은 경우 ping 명령을 실행하면 (예 : -c 3 옵션으로 3번만 시도) 진행 과정이 실시간으로 출력되지 않고 시간이 걸려 모든 결과가 출력되면 화면에 보이게 됩니다.





반응형

댓글()