0

i am trying to check for internet connection in my application. first, i am checking if wifi or mobile data is on, then i am checking if there is an active internet connection. what i am currently doing:

    public class ConnectivityReceiver extends BroadcastReceiver {

    String TAG="ConnectivityReceiver";

public static boolean hasInternetAccess() {
    try {
        HttpURLConnection urlc = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                        .openConnection());
        urlc.setRequestProperty("User-Agent", "Android");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500);
        urlc.connect();
        return (urlc.getResponseCode() == 204 &&
                urlc.getContentLength() == 0);
    } catch (IOException e) {

    }

    return false;
}


@Override
public void onReceive(Context arg0, Intent intent) {
      String action = intent.getAction();


        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
         if(noConnectivity){
             try{

                 TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
             }
             catch(Exception e)
             {

             }
         }
         else
         {
             Boolean status = hasInternetAccess();
             if(status==true)
             {
                 try{
                     TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_wifi);
                 }
                 catch(Exception e)
                 {

                 }
             }
             else
             {
                 try{

                     TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
                 }
                 catch(Exception e)
                 {

                 }
             }


         }


}

but i am getting the following error:

java.lang.RuntimeException: Unable to start receiver connectionchecker.ConnectivityReceiver: android.os.NetworkOnMainThreadException
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2668)
            at android.app.ActivityThread.access$1800(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
            at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
            at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
            at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390)
            at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343)
            at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
            at connectionchecker.NetworkUtil.hasInternetAccess(NetworkUtil.java:21)
            at connectionchecker.ConnectivityReceiver.onReceive(ConnectivityReceiver.java:46)
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2653)
            at android.app.ActivityThread.access$1800(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
Rashad.Z
  • 2,494
  • 2
  • 27
  • 58

3 Answers3

3

You are trying to connect to the network in UI thread which is not allowed. to check for active internet connection use following method.

public boolean isConnected() {
    ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
        return true;
    } else {
        return false;

    }
}

Once you receive the value, if it is true proceed with network operation. Else display the user a proper error message.

Vilas
  • 1,695
  • 1
  • 13
  • 13
0
Caused by: android.os.NetworkOnMainThreadException

You need to perform network operation not on UIthread.

Udi Oshi
  • 6,787
  • 7
  • 47
  • 65
  • so how can i call it in the broadcast reciever or to check the internet connection once it is changed or lost (wifi is connected but no interent access) – Rashad.Z Feb 02 '15 at 15:06
0

Sounds like you might need to use the getActiveNetworkInfo() call. There is a few posts on stackoverflow already that document it extensively so rather than repeat those have a look at these:

Detect whether there is an Internet connection available on Android

Community
  • 1
  • 1
JodiMiddleton
  • 310
  • 1
  • 8
  • i checked the link but this only checks if wifi or mobile data are turned on and not if the internet is reachable – Rashad.Z Feb 02 '15 at 15:04