Android開發中網絡相關的檢測包括網絡是否正常連接和網絡已連接但是否可以正常訪問兩類。
(1)其中最常用的就是網絡連接是否正常的檢測,具體的代碼如下:
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// 獲取代表聯網狀態的NetWorkInfo對象
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
if (networkInfo == null) {
return false;
}
boolean available = networkInfo.isAvailable();
if (available) {
Logs.i(TAG, "當前的網絡連接可用");
} else {
Logs.i(TAG, "當前的網絡連接不可用");
}
return available ;
(2)對於網絡已連接,但是需要判斷是否可以正常訪問的問題,其實我們可以使用ping的方式進行檢測,經過查閱網上的資料,發現好多使用 Process process=Runtime.getRuntime().exec("/system/bin/ping -c 4 "+"www.baidu.com") 進行檢測的,經過測試發現會拋IOException異常,提示相關目錄也就是/system/bin/ping 這個找不見,主要原因是系統沒有root,所以無法訪問系統目錄。因此這種方式肯定不是我們想要的,那麼我們該如何實現呢?其實不要慌,我們可以採用如下這種方式就可以實現我們想要的效果
Process process=Runtime.getRuntime().exec("ping -c 1 -w 1 " + "www.baidu.com");
具體的知識及實現可參考如下:
Ping是Windows、Unix和Linux系統下的一個命令。ping也屬於一個通信協議,是TCP/IP協議的一部分。利用“ping”命令可以檢查網絡是否連通,可以很好地幫助我們分析和判定網絡故障
Ping發送一個ICMP(Internet Control Messages Protocol)即因特網信報控制協議,回聲請求消息給目的地並報告是否收到所希望的ICMP echo (ICMP回聲應答),用來檢查網絡是否通暢或者網絡連接速度的命令。廣義來說即發送一個數據包,根據返回的數據包得到丟包率及平均時間得出網絡的連接狀態。
ping命令可以用在android中檢測網絡ip或者socket的連接,命令格式:ping ip地址(最簡)
ping具有一些參數,可以具體定義包的個數、包的最大存活時間等
-c 發送ICMP包的個數
-i 每次發送數據包中間的間隔時間,單位秒
-l <前置載入> 設置在送出要求信息之前,先行發出的數據包
-s 設置數據包的大小
-t 設置TTL(存活數值)的大小 / TTL : Time to Live該字段指定IP包被路由器丟棄之前允許通過的最大網段數量
-w deadline 數據包存活最大時間
-W timeout等待每個響應的最長時間,單位爲秒
android ping檢測ip地址或socket地址可使用兩種方式:
一種是使用Runtime.getRuntime().exec()執行ping命令,根據方法返回值process是否連通判斷連接狀態
process 的 waitFor() 方法源碼中的解釋:
/**
* Causes the calling thread to wait for the native process associated with
* this object to finish executing.
*
* @return the exit value of the native process being waited on.
* @throws InterruptedException
* if the calling thread is interrupted.
*/
public abstract int waitFor() throws InterruptedException;
必要的情況下,此方法會使當前線程一直處於阻塞狀態直到此執行進程從結果上表現出終止。此方法會在子進程被終止的時候立即返回值。如果子進程沒有被終止,則當前線程一直阻塞到子進程退出。
return:一般來說 0 表示正常停止,即正常完成,未出現異常情況。1 表示網絡已連接,但是無法訪問,2 表示網絡未連接。
示例:
Process p = Runtime.getRuntime().exec("ping -c 1 -w 1 " + ipString);
// 讀取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);
}
// PING的狀態
int status = p.waitFor();
if (status == 0) {
sleep(3000);
} else {
isEnable = false;
ExDispatcher.dispatchMessage(ExMessage.PING_CONNECT_BREAK);
interrupt();
}
另一種使用ping命令中發包及包的丟失率判斷通信的連接狀態
Process process = Runtime.getRuntime().exec("ping "+address);
InputStreamReader r = new InputStreamReader(process.getInputStream());
LineNumberReader returnData = new LineNumberReader(r);
String returnMsg="";
String line = "";
while ((line = returnData.readLine()) != null) {
System.out.println(line);
returnMsg += line;
}
if(returnMsg.indexOf("100% loss")!=-1){
System.out.println("與 " +address +" 連接不暢通.");
} else{
System.out.println("與 " +address +" 連接暢通.");
}
正常的ping檢測結果一般爲:
====receive====:PING 192.168.43.159 (192.168.43.159) 56(84) bytes of data.
====receive====:64 bytes from 192.168.43.159: icmp_seq=1 ttl=64 time=73.8 ms
====receive====:64 bytes from 192.168.43.159: icmp_seq=2 ttl=64 time=91.4 ms
====receive====:64 bytes from 192.168.43.159: icmp_seq=3 ttl=64 time=1.18 ms
====receive====:64 bytes from 192.168.43.159: icmp_seq=4 ttl=64 time=139 ms
====receive====:--- 192.168.43.159 ping statistics ---
====receive====:4 packets transmitted, 4 received, 0% packet loss, time 3004ms
丟包率爲100%時則網絡爲斷開狀態,上述結果顯示發送爲4個數據包,丟包率爲0,連接正常
參考鏈接:https://blog.csdn.net/u011069604/article/details/73135531