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

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

想到瞭用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;

}

發佈留言