Friday 26 July 2013

Check Network Connectivity In Android

Leave a Comment
Today Android Application have lot of dependency on the network to perform functionality. So it is very important to find out if is our device connected to the network before performing any network related task. So, how will you find out if your device connected to the network programmatically.
Lets follow the following steps:-
I have made a separate class to check connection, named CheckConnection.java
This class will help you to find out the network connection of your device. Just create the instance of the class where ever you want to check the network connection, and pass the context of that activity to the CheckConnection.java Class.

// follow the following code

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

public class CheckConnection {
    NetworkInfo networkInfo, mobileInfo;
    WifiManager wifiSpeedTest;
    Context context;

    public CheckConnection(Context context) {    
        this.context = context;
    }

    public Boolean checkNow() {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            networkInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            mobileInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (networkInfo.isConnected() || mobileInfo.isConnected()) {
                return true;
            }
        } catch (Exception e) {
            System.out
                    .println("CheckConnectivity Exception: " + e.getMessage());
        }

        return false;
    }

}

0 comments:

Post a Comment