특정 주소에 네트워크 연결상태를 확인하기 위해서 ping을 사용한다.
Kotlin
val networkThread = Thread {
try {
val runTime = Runtime.getRuntime()
val cmd = "ping -c 1 -W 2 $ip" //ip는 test 하고 싶은 주소 String 을 넣어주면 된다.
val proc = runTime.exec(cmd)
proc.waitFor()
//여기서 반환되는 ping 테스트의 결과 값은 0, 1, 2 중 하나이다.
// 0 : 성공, 1 : fail, 2 : error
val result = proc.exitValue()
when (result) {
0 -> Log.d("FragmentSelfCheck", ip.toString() + " - Ping Success")
1 -> Log.d("FragmentSelfCheck", ip.toString() + " - Ping Fail")
else -> Log.d("FragmentSelfCheck", ip.toString() + " - Ping Error")
}
} catch (e: Exception) {
when(e){
is InterruptedException, is IOException -> {
Log.d("FragmentSelfCheck", ip + e.message)
}
}
}
}
networkThread.start()
Java
networkThread = new Thread(() -> {
try {
Runtime runTime = Runtime.getRuntime();
String cmd = "ping -c 1 -W 2 "+ ip; //ip는 test 하고 싶은 주소를 넣어주면 된다.
Process proc = null;
proc = runTime.exec(cmd);
proc.waitFor();
//여기서 반환되는 ping 테스트의 결과 값은 0, 1, 2 중 하나이다.
// 0 : 성공, 1 : fail, 2 : error
int result = proc.exitValue();
switch (result){
case 0:
Log.d("FragmentSelfCheck", ip + " - Ping Success");
break;
case 1:
Log.d("FragmentSelfCheck", ip + " - Ping Fail");
break;
default:
Log.d("FragmentSelfCheck", ip + " - Ping Error");
break;
}
}catch (InterruptedException | IOException e){
Log.d("FragmentSelfCheck", ip + e.getMessage());
}
});
networkThread.start();
* 옵션은 대소문자를 구분하니 주의
-c 옵션은 ping을 날릴 횟수
-W 옵션은 ping을 날린 이후 return 결과를 기다릴 timeout 시간 값이다.
연결 상태가 끊겼거나 연결 상태가 좋지 않을때 이 대기 시간 동안 응답이 없으면 연결 실패로 간주
return되어 오는 결과 값에 따라 원하는 처리를 하면 되겠다.
Thread를 사용한 이유는 주의할 점이 waitFor()에서 스레드가 멈추기 때문에 (Thread.sleep()과 같이)
MainThread가 아닌 새로 생성한 Thread에서 호출해줄 필요가 있다.
Thread 사용없이 그냥 사용해본 결과 핑을 대기중에는 UI조작이 매끄럽지 못 할 수 있다.
Kotlin이라면 보단 Coroutine으로 사용해야겠다.
'Kotlin > Util' 카테고리의 다른 글
Kotlin 소수 판별 함수 (0) | 2022.03.15 |
---|---|
마스킹 함수 ( * 처리 표시 ) (0) | 2022.01.10 |
TimerUtil 일정시간이후 특정동작 지정 수행 (0) | 2021.04.21 |
DecimalFormat을 사용한 가격 , 표시 (0) | 2020.11.27 |