0

I'm working on an Android projet and I need to know when the user have access to internet. (not just if the wifi is activated. For example in case where the user used a hotspot wifi connection)

I use this method :

public static boolean isOnline(final Context context) {
    boolean result = false;
    ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connec.getNetworkInfo(0).isConnectedOrConnecting() || connec.getNetworkInfo(1).isConnectedOrConnecting()) {
        URL url = new URL("https://www.google.fr");
        URLConnection urlConnection;
        urlConnection = url.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
        int responseCode = httpConnection.getResponseCode();
        result = (responseCode == 200);
    }
    return result;
}

This method works but slows down my application because it's use in a Timer which checks the connection of the user each 5 seconds. And I need to know in real time the connection state of the user...

Somebody know an other way to verify the internet connection ? Maybe with java reflection...?

animuson
  • 53,861
  • 28
  • 137
  • 147
  • Maybe you can find something in this question: http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts – Jens Vossnack Aug 06 '13 at 13:16
  • Thank you for this quick answer ! :-) I'll look at it. – Guillaume Macke Aug 06 '13 at 13:28
  • Why on earth do you need to check network availability every *five seconds*? You're going to drain the battery pretty quickly. If you need to transfer data *that* often, just transfer the data without using a separate is-online check first; the data transfer request itself will tell you when you're offline. – Barend Aug 06 '13 at 13:44
  • I don't find an answers to my question. Everybody make a test on the NetworkInfo or ping a web url to know if the device is connected. I cannot do a ping because it slow down my application... In addition, if the web site at the URL has crashed, the ping will fail even if the device is connected... – Guillaume Macke Aug 06 '13 at 14:33

1 Answers1

-2
ConnectivityManager mConnMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

public boolean hasWifi() {
    return mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null
            && mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
}

Is this what you want ?

Weibo
  • 1,042
  • 8
  • 18
  • The method doesn't work if the device are connected to a hotspot Wifi. You are effectively connected to the Wifi, but when you try to launch a request, for example on the google web site, you will be redirect to the portal of the hotspot... – Guillaume Macke Aug 06 '13 at 14:44