본문 바로가기

공부/안드로이드

안드로이드에서 커맨드 명령어 날려서 결과 확인하기

public static int isHostReachable(String hostIP, String where){
Process process;
Runtime runtime = Runtime.getRuntime();
int hostReachResult = NETWORK_UNREACHABLE;
try{
String cmd = "ping -c 1 -i 4 -w 3 "+hostIP; //shell에서 실행할 명령, c: 횟수, i:간격, w:핑테스트 종료 시간
DEBUG.log("isHostReachable", "where : "+where);
DEBUG.log("isHostReachable", "cmd : "+cmd);

process = runtime.exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while((line = br.readLine()) != null){
DEBUG.log("isHostReachable", line);
if(line.contains("1 received")){//결과 문자열 중 "1 received" 문구가 포함되어있으면 성공
hostReachResult = NETWORK_REACHABLE;
break;
}
}
DEBUG.log("isHostReachable", "result : "+hostReachResult);
}catch(Exception e){
DEBUG.loge("isHostReachable", "Unable to execute command");
}
return hostReachResult;
}