android 检测网络状态

 public boolean isConnectingToInternet() {
  ConnectivityManager connectivity = (ConnectivityManager) MainActivity.this
    .getSystemService(Context.CONNECTIVITY_SERVICE);
  if (connectivity != null) {
   NetworkInfo[] info = connectivity.getAllNetworkInfo();
   if (info != null)
    for (int i = 0; i < info.length; i++)
     if (info[i].getState() == NetworkInfo.State.CONNECTED) {
      return true;
     }
  }
  return false;
 }

 

//或者

 

 private boolean isOpenNetwork() {
  ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  if (connManager.getActiveNetworkInfo() != null) {
   return connManager.getActiveNetworkInfo().isAvailable();
  }

  return false;
 }

你可能感兴趣的:(Android)