Java: Check Internet connection on Android Device (Wifi or Mobile)

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 Internet connection on Android Device (Wifi or Mobile data)

Have Questions? Post them here!

Recent Posts:

Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.