How to check if internet is available or not in app startup in android?

android, connectivity

Solution

You can use my method:

public static boolean isNetworkAvailable(Context context) 
{
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null) 
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();

        if (info != null) 
        {
            for (int i = 0; i < info.length; i++) 
            {
                Log.i("Class", info[i].getState().toString());
                if (info[i].getState() == NetworkInfo.State.CONNECTED) 
                {
                    return true;
                }
            }
        }
    }
    return false;
}

Problem

My app at first loads the datas from internet(I am using webservice) I want to check internet access at app startup. - I will like to check if any forms of internet either 3G or WIFI or GPRS or any other is available or not. - If not available, give message to user like "You need internet access" and exit the app. (Currently i am getting force close error in my app if there is no internet access) - If availabe, start my app normally. - Also, my app is fetches the datas from webservice at different phase, before each phase or operation, i will like to check internet access at first. How do i do this ?

Original source

Related problems