Mahoni
Mahoni

Reputation: 7466

Testing for connectivity not working properly

Before doing networking connection stuff I use this code to set connectivity. If it is NONE it's not possible, displaying an error. Now I am getting lots of user reports of user complaning about this error message, telling me that they are able to use the internet on other apps.

final NetworkInfo activeNetwork = connectionManager.getActiveNetworkInfo();
if (activeNetwork == null || !activeNetwork.isConnected()) {
        newNetworkType = NetworkStatus.NONE;
} else {
        if (activeNetwork.getTypeName().equalsIgnoreCase("MOBILE")) {
                newNetworkType = NetworkStatus.LOW;
        } else {
                newNetworkType = NetworkStatus.HIGH;
        }
}

This code is hooked to a NetworkChangedReceiver, updating it constantly. Now I am wondering if this code is not working properly. Should I rely on other methods? For instance does activeNetwork == null really mean that there is no internet connection? Should I maybe use NetworkInfo.isAvailable instead of isConnected? What about isConnecting?

Upvotes: 0

Views: 31

Answers (1)

MDMalik
MDMalik

Reputation: 4001

Well I had many issues with this code. Hence I opted for a different route completely.

What I do is, I ping the website which I'm going to communicate with.
It helps in two things

a) To check the condition of your internet
b) Is your website online or not

HttpURLConnection connection = null;
try {
    URL u = new URL("http://www.yourwebsite.com/");
    connection = (HttpURLConnection) u.openConnection();
    connection.setRequestMethod("HEAD");
    int code = connection.getResponseCode();
    // You can determine on HTTP return code received. 200 is success.
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    if (connection != null) {
        connection.disconnect();
    }
}

Upvotes: 1

Related Questions