-1
The following is the code used to check network connectivity

package com.app.helper;

import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class NetworkHelper {

/*It checks whether network connection is available or not. 
 * */

public static boolean isOnline(Context cxt) {

    ConnectivityManager cm = (ConnectivityManager) cxt
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting() &&  canHit()) {

        Log.d(UMobileApp.TAG,"In NetworkHelper :connection  available");
        return true;
    }

    return false;
}

/* It checks whether connection to the URL can be established or not.
 * Also a timout is set to 3000ms. */ 

public static boolean canHit() {

    try {

        URL url = new URL("http://www.google.com/");
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        urlConnection.setConnectTimeout(3000);
        urlConnection.connect();
        urlConnection.disconnect();
        return true;

    } catch (Exception e) {         
        Log.e(UMobileApp.TAG,"Exception In NetworkHelper   :"+e.getMessage());
        e.printStackTrace();
        return false;
    } 
}

/* To exit if the network connection is not available.*/

public static void exitIfOffline(Activity act) {
    if (!isOnline(act.getApplicationContext())) {
         MessageBox.alert(act.getResources().getString(R.string.no_connection_found ), act, true);
    }
}

}

Here I am checking the network connectivity through the static method isOnline. Now the problem is using the above approach, the network works fine for api level 9 and below, but otherwise it returns false as the boolean value. Spent almost 3 hours to detect this anomaly. Do we really need to check for network connection based on api levels or is there a generic method which returns the same value for all api levels

XylemRaj
  • 772
  • 4
  • 13
  • 28
  • 3
    I think you are doing N/W operation on UI thread (Which is not allowed after API level 11). Check this : http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Prashant Jun 23 '15 at 12:30
  • No, there is no problem as such – XylemRaj Jun 23 '15 at 12:32
  • 1
    People are still asking "NetworkOnMainThreadException" questions in 2015.. Interesting... The fact that you chose to catch Exception (hint : you should **never** do that unless you **want** to spend 3 hours debugging stuff) but did not look at the stack trace indicates you should read more about the basics of Java. – 2Dee Jun 23 '15 at 13:01

1 Answers1

0

I am Using code given below which is working fine for all API levels, try this once

Don't forget this permission

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

Once I have faced issue with API level 16 that along with access network state permission we have to provide wifi state permission, I know this is weird but try this once.

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



public class NetworkConnectionUtils{

        public static boolean isNetworkConnected(Context mContext) {

            ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connectivityManager== null) {

                Log.v(TAG,"couldn't get connectivity manager");

            } else {

                NetworkInfo[] networkInfo= connectivityManager.getAllNetworkInfo();

                if (networkInfo!= null) {

                    for (int i = 0; i < networkInfo.length; i++) {

                        if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {

                            return true;
                        }
                    }
                }
            }

            return false;

        }
    }
Mohd Mufiz
  • 2,236
  • 17
  • 28