Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5404636
  • 博文数量: 763
  • 博客积分: 12108
  • 博客等级: 上将
  • 技术积分: 15717
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-28 21:21
个人简介

业精于勤,荒于嬉

文章分类

全部博文(763)

文章存档

2018年(6)

2017年(15)

2016年(2)

2015年(31)

2014年(14)

2013年(87)

2012年(75)

2011年(94)

2010年(190)

2009年(38)

2008年(183)

2007年(28)

分类: Android平台

2015-10-23 18:21:11

有时候我们连接上一个没有外网连接的WiFi或者有线就会出现这种极端的情况,目前Android SDK还不能识别这种情况,一般的解决办法就是ping一个外网。



  1. /* @author suncat
  2.  * @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
  3.  * @return
  4.  */
  5. public static final boolean ping() {


  6.     String result = null;
  7.     try {
  8.             String ip = "";// ping 的地址,可以换成任何一种可靠的外网
  9.             Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
  10.             // 读取ping的内容,可以不加
  11.             InputStream input = p.getInputStream();
  12.             BufferedReader in = new BufferedReader(new InputStreamReader(input));
  13.             StringBuffer stringBuffer = new StringBuffer();
  14.             String content = "";
  15.             while ((content = in.readLine()) != null) {
  16.                     stringBuffer.append(content);
  17.             }
  18.             Log.d("------ping-----", "result content : " + stringBuffer.toString());
  19.             // ping的状态
  20.             int status = p.waitFor();
  21.             if (status == 0) {
  22.                     result = "success";
  23.                     return true;
  24.             } else {
  25.                     result = "failed";
  26.             }
  27.     } catch (IOException e) {
  28.             result = "IOException";
  29.     } catch (InterruptedException e) {
  30.             result = "InterruptedException";
  31.     } finally {
  32.             Log.d("----result---", "result = " + result);
  33.     }
  34.     return false;
  35. }




阅读(2769) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~