본문 바로가기

IT개발/안드로이드

안드로이드 소스에서 shell 명령어 실행하기

안드로이드는 리눅스 기반이어서 adb shell을 실행하면 디바이스에서 실행되는 shell 모드로 들어가게 된다.

간단한 ls 명령어를 실행한 모습..

 

그런데 소스 레벨에서 이런 명령어를 실행하고 싶을때가 있다.

특정 프로세스를 실행한다던가, 파일 입출력을 실행한다던가, 시스템 자원을 모니터링 한다던가…

아래는 top 명령어를 통해, 시스템 자원을 로그로 내보내는 간단한 코드 이다.

 

        Runtime runtime = Runtime.getRuntime(); 
        Process process; 
        String res = "-0-"; 
        try { 
                String cmd = "top -n 1"; 
                process = runtime.exec(cmd); 
                BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); 
                String line ; 
                while ((line = br.readLine()) != null) { 
                 Log.i("test",line);
                } 
        } catch (Exception e) { 
                e.fillInStackTrace(); 
                Log.e("Process Manager", "Unable to execute top command"); 
        }


핵심 라인 > 
process = runtime.exec(cmd);