소프트웨어/안드로이드
[안드로이드] 코드에서 Ping 확인
이로이로
2020. 4. 28. 17:20
Java
/**
* @return 0: success, 1: fail, 2: error
*/
public static int ping(@NonNull String host, int timeout) throws InterruptedException, IOException {
int res;
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(String.format(Locale.US, "ping -c 1 -W %d %s", timeout, host));
// 0: 성공, 1: 실패, 2: 에러
res = process.waitFor();
// ~~
// shell 명령 출력 값 확인용입니다. 없어도 되요
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
Log.d(TAG, "cmd output:" + line);
}
return res;
}
Kotlin
companion object {
/**
* @return 0: success, 1: fail, 2: error
*/
fun ping(host: String, timeout: Int): Int {
val res: Int
val rt = Runtime.getRuntime()
val process = rt.exec(String.format("ping -c 1 -W %d %s", timeout, host));
// 0: 성공, 1: 실패, 2: 에러
res = process.waitFor()
// ~~
// shell 명령 출력 값 확인용입니다. 없어도 되요
val br = BufferedReader(InputStreamReader(process.inputStream))
br.lineSequence().forEach {line ->
Log.d(TAG, "cmd output:$line")
}
return res
}
}
위와 같이 하면 됩니다.
주의할 점은 waitFor에서 스레드가 멈추기 때문에 (Thread.sleep()과 같이) MainThread가 아닌 새로 생성한 Thread에서 호출해줘야합니다.