January 4, 2017

Android How to Check Internet Connection Status

By Lalit Vasan


If you are developing an android application that perform internet related operations like calling web API, loading web page in Web View, uploading profile pic and etc. So before performing any internet related tasks it is better to first check that your device is connected to internet or not . Android provides ConnectivityManager class to know about the internet connection status. The following method will be very useful to know internet connection state.

First add the INTERNET and ACCESS_NETWORK_STATE permission to AndroidManifest.xml

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

Then use the below method to check if the device is connected to internet or not. This method will return true if the device is connected to internet.

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

Enjoy Coding and Share Knowledge