Java code to check Internet Connection on Android Device Programmatically


Android code snippet to check if Internet connectivity is available on Android devices and is active. Check connections like Wifi and Mobile Subscriber Internet connections like 2g, 3g, 4g, etc.

ConnectivityManager is the class you can make use of to achieve this, use getSystemService(Context.CONNECTIVITY_SERVICE) that returns an ConnectivityManager object, now using this connection manager you can get information of all networks as an NetworkInfo[] array. Iterate through this array and check what type of network is currently active with the device - WIFI or MOBILE using netInfo.getTypeName().equalsIgnoreCase(TYPE).

private boolean checkNetwork() {
        boolean wifiAvailable = false;
        boolean mobileAvailable = false;
        ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfo = conManager.getAllNetworkInfo();
        for (NetworkInfo netInfo : networkInfo) {
            if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
                if (netInfo.isConnected())
                    wifiAvailable = true;
            if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
                if (netInfo.isConnected())
                    mobileAvailable = true;
        }
        return wifiAvailable || mobileAvailable;
    }

If you see any error in the logCat, it could be that you have missed adding the required permissions!

⚠️ Add the following User Permission: android.permission.ACCESS_NETWORK_STATE

Android - Check the Internet connection on Android Device (Wifi or Mobile data)


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap