Android 中网络连接检测和使用ping检测网络是否可访问

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yyanjun/article/details/81197991

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

猜你喜欢

转载自blog.csdn.net/yyanjun/article/details/81197991