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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With