Internet connectivity check in Android

1. Checking the CONNECTIVITY_SERVICE and if the NetworkInfo is connected or connecting. This check if pretty fast, takes about 20ms on average. This could be showing there is internet but cannot tell how fast the connectivity is.

public static boolean networkStateCheck(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

2. Checking if there is internet connection by making an url connection.

public static boolean urlCheck(String url, int timeout) {
    try {
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

3. Checking if there is internet connection by making a socket connection.

public static boolean socketCheck(String host, int port, int timeout) {
    try {
        long start = System.currentTimeMillis();
        Socket socket = new Socket();
        InetSocketAddress addr = new InetSocketAddress(host, port);
        Log.d("NetworkUtil", "InetSocketAddress time taken: " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        socket.connect(addr, timeout);
        Log.d("NetworkUtil", "connect time taken: " + (System.currentTimeMillis() - start));
        socket.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

To run any of the above methods in Android, make sure the INTERNET and ACCESS_NETWORK_STATE permissions are enabled in the manifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Also make sure they are ran in a background thread, or you will get android.os.NetworkOnMainThreadException

new Thread(new Runnable() {
    @Override
    public void run() {
        boolean isOnline = socketCheck("www.google.com", 443, 100);
        Log.d(TAG, "####################online status>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " + isOnline);
    }
}).start();

Search within Codexpedia

Custom Search

Search the entire web

Custom Search