Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android networkinfo always returns true even if internet is not available

This code always returns true. This gets called when a Login button is pressed. I first tried with wifi connected (on emulator). It returned true and then I disconnected wifi and then tried. it still returns true.

public static boolean isNetworkAvailable( Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            // if no network is available networkInfo will be null
            // otherwise check if we are connected
            if (networkInfo != null && networkInfo.isConnected()) {
                 State network = networkInfo.getState();
                 Log.d("here", "true");
                 return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING);

            }
            Log.d("here1", "false");
            return false;
}
like image 311
Kevin Rave Avatar asked Sep 15 '12 22:09

Kevin Rave


1 Answers

This code works on-device, as I'm using something very similar in one of my apps. Keep in mind that this code will tell you whether you are connected to a network, not whether the network you are connected to has internet connectivity. If you're using the emulator, it's always connected via 3G simulation, so disconnecting your computer's wifi won't change that. You could put the emulator in airplane mode, which should give you the "false" you were looking for.

What I've done in my apps is to create a service which receives network change broadcasts. Once a network is connected, it then tries to download a known (small) file over the internet. Only if that succeeds will it then broadcast an internet-available intent to all the activities, which can then change state based on this.

like image 157
323go Avatar answered Nov 13 '22 05:11

323go