Shawn Henderson Shawn Henderson - 3 months ago 23
Android Question

Check online status android

Im using this code to check if the device is online as the app loads.

public boolean isOnline()
ConnectivityManager connMgr = (ConnectivityManager)
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());

But this ALWAYS returns true, even if it have the computer Wifi turned off for testing. Is this function just testing for the ability to connect or actual connection?



Try using:

private boolean isOnline()
            ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo().isConnectedOrConnecting(); 
        catch (Exception e)
            return false;

Where mContext is the context you're using.

My guess is that your code would work fine on a device, but you may be testing on an emulator. I've noticed that sometimes the emulator stays connected even when the computer's internet if switched off. To achieve correct functionality, you should go into the settings and disable WiFi and Mobile data from there, instead of turning the computer WiFi off.

In addition, the code I gave above would also return true if the device is in the process of connecting, while the one you were using would only return true if you already had an established connection.