简体   繁体   中英

check if device is really connected to the internet android

I am developing an android application and I need to check whether the device is really connected to the internet using the following the method

cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm.getActiveNetworkInfo() != null
                    && cm.getActiveNetworkInfo().isAvailable()
                    && cm.getActiveNetworkInfo().isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(10 * 1000); // Ten seconds timeout in milliseconds
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) { // success
                        System.out.println("success mobile");
                        return true;
                    } else { // Fail
                        return false;
                    }
                } catch (IOException e) {
                    return false;
                }
            } 
            else 
            {
                return false;
            }

this method works if I disable the mobile data or the wifi. However, in my case the provider simply stopped the internet because I've reached my usage limit or run out of data allowance. So in this case the method returns TRUE even though when I go to the browser and type in google.com it doesn't work and I get the message by the provider that I've reached my limit? So somehow google.com pings as reachable even though I can't open it from the device due to the usage limit? I can only access the webpage of my mobile provider where I can buy more allowance so the internet is not switched off but just limited. How can I check for that?

The best way to do this is to implement time out exception.

 HttpGet httpGet = new HttpGet(url); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httpGet); 

You could Ping well known public site(s) such as Google's public DNS servers: 8.8.8.8 and 8.8.4.4 , www.cnn.com , www.yahoo.com , etc.

This will be a good way to do a 'sanity' check. (make sure to do this in a background thread in case the device is NOT connected to the internet. Plus I'd mix/match 1 IP and 1 Domain name, that way you can maybe tell the user 'why' your app isn't connecting.

But you should probably only do this AFTER your connection attempt to YOUR server fails. (as that sanity check to tell if YOUR site is down or not)


THEN if you are able to ping those sites, then try full HTTP connect and verify that the 'page' you are getting is 'correct'. Not just the HTTP response code. Because the HTTP MITM (Man in the middle) that your ISP is probably using to redirect your web traffic is going to return 200 because it is a 'valid' page... but not 'the desired' page.

You could easily check THIS part by making a few byte webpage on your server that has nothing but a HTML Title of 'HTTP CHECK' and 'GOOD' or something like that in the body. Then validate that your app gets THAT page (actually check the HTML contents) and not 'something else' (such as a Paywall).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM