Jeris Jeris - 1 month ago 10
Android Question

Best way to check for internet connection in android

I am developing an

android
app and I want to know the best way to check if internet connection is present or not. I have tried using
connectivity manager
and
networkinfo
class but to no avail as my app keeps on crashing without net or else do I go
HttpConnection
method. Can someone give their valuable suggestions.

Answer
    URL myurl = new URL(url);
    URLConnection connection = myurl.openConnection();
    connection.setConnectTimeout(20 * 1000);
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    int responseCode = -1;
    try {
        responseCode = httpConnection.getResponseCode();
    } catch (Exception e1) {                    
            throw e1;                   
    }
    if (responseCode == HttpURLConnection.HTTP_OK) {
          //connection is OK and do what you want
          //...
    }
    else
    {
          //connection is not OK
          httpConnection.disconnect();
    }