android监听当前的网络

jopen 9年前

之前我听腾讯一个同事说,用android原本的监听网络方式,是不能保证的,原因是,现在的WiFi都需要通过浏览器验证

所以采用ping ip才能保证网络是连通的。

public class NetUtils {      private final static String TAG = "NetUtils";        /**       * 判断当前网络是否打开       *       * @param context       * @return       */      public static boolean isNetOpen(Context context) {          boolean bisConnFlag = false;          ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);          NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();          if (activeNetworkInfo != null) {              bisConnFlag = connectivityManager.getActiveNetworkInfo().isAvailable();          }          return bisConnFlag;      }        /**       * 判断是否为WiFi       *       * @param context       * @return       */      public static boolean isWifi(Context context) {          ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);          NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();          if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {              return true;          }          return false;      }        public static final boolean ping(String ip) {          String result = null;          try {              String testIP = "baidu.com";              if (!TextUtils.isEmpty(ip)) {                  testIP = ip;              }              Process process = Runtime.getRuntime().exec("ping -c 3 -w 100 " + testIP);//ping 3次              //读取ping的内容              InputStream inputStream = process.getInputStream();              BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));              StringBuffer stringBuffer = new StringBuffer();              String content = "";              while ((content = bufferedReader.readLine()) != null) {                  stringBuffer.append(content);              }              Log.e(TAG, "result content:" + stringBuffer.toString());              //ping的状态              int status = process.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.e(TAG, result);          }          return false;      }  }


来自: http://my.oschina.net/moziqi/blog/531937?fromerr