Jeris Jeris - 1 year ago 77
Android Question

Best way to check for internet connection in android

I am developing an

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

Answer Source
    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
          //connection is not OK
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download