简体   繁体   中英

How to check if network is available

I am writing an app which sends some data to the server by POST method and receives a response. To do this, I firstly need to check if network is available. I am using this method:

private boolean isNetworkAvailable() {
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connManager.getActiveNetworkInfo();

    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

However, this function is not very accurate. For example, sometimes my device network indicator in status bar shows that it is currently connected to an EDGE network or a 3G network, but when I try to access the network, it starts changing immediately to another network type and changing back and there is no actual valid connection, but this function still returns true . How to make sure that the network connection is valid and data can be sent through it?

I don't think there is straight away API to check if a connection is valid. you can only detect if you are connected to a router or not. You can try to connect to a known stable domain to check if it connects. But you add extra delay in connection to do this check

You have to try connect to server and get response code to check connection.

try this.

public boolean isOnline(Context context) {
try {
    ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
        URL url = new URL("http://www.ripansekhon.blogspot.com");
        HttpURLConnection urlc = (HttpURLConnection) url .openConnection();
        urlc.setRequestProperty("User-Agent", "test");
        urlc.setRequestProperty("Connection", "close"); 
        urlc.setConnectTimeout(1000); // mTimeout is in seconds
        urlc.connect();
        if (urlc.getResponseCode() == 200) {
            return true;
        } else {
            return false;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
return false;

}

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