March 14, 2018

How to check Network Availability

On this blog I am going to explain how to check internet connection is present or not. For this we are  using ConnectivityManager and NetworkInfo. For this first you need to add the permission on your AndroidManifest.xml file. 

Adding Permission
We required INTERNET and ACCESS_NETWORK_STATE. We need to add these permisions inside <application> </application> tag. Here is the permission code.

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

Java Code
I created a function  isOnline(Context con) to check the internet is there or not. This function will return the network status if the internet is connected or not.

public static boolean isOnline(Context con) {
    boolean connected = false;
    ConnectivityManager connectivityManager;
    try {
        connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isConnected();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return connected;
}