由于做的项目是机顶盒,需要用到实时来检测网络,服务器是否在线,之前是用来访问服务器上面的一个文件,如果成功就是服务器存在,如果访问失败就是不存在,但是发现这样并不行,找了好多方法最后使用Ping的方法来实现此功能
突然想起来看看工具类,在工具类里面找到了一个方法
1 /** 2 * @author cat 3 * @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网) 4 * @return 5 */ 6 public final boolean ping(String urld) { 7 8 String result = null; 9 try { 10 String ip = urld;// 除非百度挂了,否则用这个应该没问题(也可以换成自己要连接的服务器地址) 11 Process p = Runtime.getRuntime().exec("ping -c 1 -w 1 " + ip);// ping3次 12 // 读取ping的内容,可不加。 13 InputStream input = p.getInputStream(); 14 BufferedReader in = new BufferedReader(new InputStreamReader(input)); 15 StringBuffer stringBuffer = new StringBuffer(); 16 String content = ""; 17 while ((content = in.readLine()) != null) { 18 stringBuffer.append(content); 19 } 20 Log.i("TTT", "result content : " + stringBuffer.toString()); 21 // PING的状态 22 int status = p.waitFor(); 23 if (status == 0) { 24 result = "successful~"; 25 return true; 26 } else { 27 result = "failed~ cannot reach the IP address"; 28 return false; 29 } 30 31 } catch (IOException e) { 32 result = "failed~ IOException"; 33 } catch (InterruptedException e) { 34 result = "failed~ InterruptedException"; 35 } finally { 36 Log.i("TTT", "result = " + result); 37 } 38 return false; 39 }
其中-c 1 是代表次数 -w 1代表的是时间,这里要注意下时间是秒,之前刚找到他的时候是写的100,一开始我以为是毫秒,后面接的IP是你服务器的地址,
先写到这里,明天见