2015. 11. 6. 15:00

원래 'adb shell'명령은 보통 컴퓨터에 디바이스를 연결해서 사용합니다.

그런데 가끔 앱 안에서도 'adb shell'명령으로 처리해야 편한 경우가 있습니다.

 

1. 간단하게 사용하기

그런 경우 'Runtime.getRuntime().exec([명령])'같이 사용할 수 있습니다.

 

예>

Runtime.getRuntime().exec("adb shell");

이런 식으로 명령을 실행하면 됩니다.

 

 

1-1. 여러 명령 한 번에 실행하기

여러 명령을 한 번에 실행하려면 'Runtime.getRuntime().exec([명령])'을 여러 번 호출하시면 됩니다.

 

예>

//adb shell을 마운트 했다가 풀어 준다.
Runtime.getRuntime().exec( "adb shell" );
Runtime.getRuntime().exec("mount -o remount,rw /system");
Runtime.getRuntime().exec("chmod 4755 /system/bin/sh" );

//Runtime.getRuntime().exec([명령]);
Runtime.getRuntime().exec("mount -o remount,rw /system");
Runtime.getRuntime().exec("chmod 755 /system/bin/sh");

 

 

1-2. 실행 후 대기

앱에서 명령을 실행한 후 명령이 끝날 때까지 기다려야 할 필요가 있을 때가 있습니다.

이럴 때는 'Process.waitFor();'를 이용하여 명령 실행이 끝날 때까지 대기할 수 있습니다.

 

예>

Process process = Runtime.exec([명령]); process.waitFor();

 

1-3. 'Process.waitFor();' 후 무한 대기 문제

'Process.waitFor();'를 사용하다 보면 쓰레드가 진행되지 않고 무한으로 기다리는 현상이 생길 때가 있습니다.

이럴 때는 스크림을 초기화하면 됩니다.

단 스크림(stream)을 초기화하면 리턴 값을 받을 수 없습니다 ㅎㅎㅎ

 

예>

Process process = Runtime.exec([명령]);
//각 스크림 지우기
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
process.waitFor();

 

 

2. 'DataOutputStream'을 이용한 방법

그런데 막상 사용해보면 위에 방법으로 명령이 실행되지 않는 경우가 있습니다.

이럴 때는 'DataOutputStream'를 사용해 봅시다.

 

예>

Process process = Runtime.exec([명령1]);
DataOutputStream dos = new DataOutputStream(process.getOutputStream());
dos.writeBytes([명령2] + "\n");
dos.flush();
dos.writeBytes("exit\n");
dos.flush();

process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();

process.waitFor();

 

 

3. '슈퍼 유저' 권한 얻어 사용하기

명령에 따라 '슈퍼 유저' 권한이 있어야 사용할 수 있는 명령이 있습니다.

PC에 연결하여 'adb shell'을 이용할 때는 상관없습니다.

하지만 앱상에서 명령을 실행하려면 필요한 경우가 있습니다.

 

슈퍼 유저 권한을 허가 받기 위해서는 폰이 루팅 되어 있어야 합니다.

아래와 같이 명령을 실행하면 해당 앱에 슈퍼 유저 권한을 줄지 물어보는 창이 뜨게 됩니다.

//슈퍼 유저 받기 
Runtime.exec('su');

 

 

마무리

사실 'adb' 명령을 쓸 일 자체가 없어야 베스트입니다.

문제는 불가항력이라는 게 있기 마련이라는 거죠 ㅎㅎㅎ