Android 用ping的方法判斷當前網路是否可用

weixin_34391854發表於2014-07-22

判斷網路的情況中,有個比較麻煩的情況就是連上了某個網路,但是那個網路無法上網 ,,, = =

想到了用ping指令來判斷,經測試,可行~ ~ ~


private static final boolean ping() {

String result = null;

try {

String ip = "www.baidu.com";// 除非百度掛了,否則用這個應該沒問題~

Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);//ping3次


// 讀取ping的內容,可不加。

InputStream input = p.getInputStream();

BufferedReader in = new BufferedReader(new InputStreamReader(input));

StringBuffer stringBuffer = new StringBuffer();

String content = "";

while ((content = in.readLine()) != null) {

stringBuffer.append(content);

}

Log.i("TTT", "result content : " + stringBuffer.toString());


// PING的狀態

int status = p.waitFor();

if (status == 0) {

result = "successful~";

return true;

} else {

result = "failed~ cannot reach the IP address";

}

} catch (IOException e) {

result = "failed~ IOException";

} catch (InterruptedException e) {

result = "failed~ InterruptedException";

} finally {

Log.i("TTT", "result = " + result);

}

return false;

}

相關文章