title: How to check connection in Android
body: <p>I have to implement a function that controls the presence of the internet connection, I need to know precisely if you can browse and not know if you are connected or not to the wifi or data.</p>
  
  <p>There may be cases where you are connected to a network but you can not browse, for example when you connect to an open wifi network (eg Mc Donalds) but to navigate you need to login, the connection available but you are not able to browse.</p>
  
  <p>In that case I would be enough to take advantage of the set timeout (but it is never considered).</p>
  
  <p>I tried to implement different functions but I can not get the desired result, for example: </p>
  
  <pre><code>public boolean checkConnection() {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
  
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo netInfo = cm.getActiveNetworkInfo();
  
      boolean response;
      if (netInfo != null &amp;&amp; netInfo.isConnected()) {
          try {
              URL url = new URL("http://www.google.it");
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setConnectTimeout(1000);
              conn.connect();
              response = conn.getResponseCode() == 200;
              conn.disconnect();
          } catch (Exception e) {
              response = false;
          }
      } else {
          response = false;
      }
      return response;
  }
  </code></pre>
  
  <p>Another function: </p>
  
  <pre><code>public boolean isInternetAvailable(String address, int port, int timeoutMs) {
      try {
          Socket sock = new Socket();
          SocketAddress sockaddr = new InetSocketAddress(address, port);
  
          sock.connect(sockaddr, timeoutMs); 
          sock.close();
  
          return true;
  
      } catch (IOException e) { return false; } }
  </code></pre>
  
  <p>This functions never takes the timeout into consideration.</p>
  
  <p>How i can solve my problem ??</p>
  
  <p>**************** EDIT 1 **************** </p>
  
  <p>I'm testing the code on a tablet connected to a network via wifi, through the firewall I blocked all connections in order to simulate the situation described in the ever question. Using the codes suggested to me you notice that the timeout value is never respected, the application goes in exception: </p>
  
  <blockquote>
    <p>Exception: java.net.UnknownHostException: Unable to resolve host
    "www.google.com": No address associated with hostname.</p>
  </blockquote>
  
  <p>The real problem is that all these functions take too long to tell me that there is no connectivity, I would need a function that responds in 1/2 sec</p>