1

My Android app can only function with WiFi connected to the Internet. Thus, I use the following code to check if the device is connected:

ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);
boolean wifi = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();

However, very often when the application is launched and WiFi connected to the Internet, I get the notification that is only shown when wifi = false. Have I missed something, or the check is not that accurate?

3
  • Same with isConnectedOrConnecting() ? I don't know about the internals of the WIFI module, but could guess that - when renewing the dhcp lease or anything like that - the state is connected. Wouldn't make much sense but pls. try. And you got the permission in your AndroidManifest.xml, don't you? Dec 1, 2010 at 14:21
  • Haven't tried, but I will. Testing this will take some time, I'll post an update when I know more. Thanks. (And I sure do have the necessary permission in the manifest.)
    – user519908
    Dec 1, 2010 at 16:10
  • Well, seems like isConnectedOrConnecting() solves the problem of "false alarm". However, it also has it's downside - if the user opens my app when the device is connecting to the Internet (though it's a matter of seconds), the app crashes.
    – user519908
    Dec 2, 2010 at 11:14

2 Answers 2

2

My project also relies on Wifi (although I use a private network). The following is my code for setting up a Wifi connection on start up:

private void initWIFI (WifiManager wifiMgr, String SSID, String key)
{
    WifiInfo curr;
    if (null == (curr = wifiMgr.getConnectionInfo()))  // Get current wifi state
    {
        joinNetwork (wifiMgr, SSID, key);
    }
    else switch (curr.getSupplicantState())
    {
        case DISCONNECTED:
        case DORMANT:
        case INACTIVE:
        case SCANNING:
            joinNetwork (wifiMgr, SSID, key);
            break;

        default:
            if (!curr.getSSID().equals (SSID))
                joinNetwork (wifiMgr, SSID, key);
    }

    while (wifiMgr.getConnectionInfo().getIpAddress() == 0)
    {
        try
        {
            Thread.sleep (1000);
        }
        catch (Exception e)
        { }
    }
}

/**This method is used to join the proper WiFi network when necessary.  Normally,
 * the Android retains network configuration and it is not necessary to manually
 * re-join the desired network on software startup. However, when it is determined
 * that the Android is not currently attached to the proper network, this function
 * is used to correct that situation. */
private void joinNetwork (WifiManager wifiMgr, String SSID, String key)
{
    try
    {
        WifiConfiguration wc         = new WifiConfiguration();

        wc.allowedAuthAlgorithms.set (WifiConfiguration.AuthAlgorithm.OPEN);
        wc.allowedAuthAlgorithms.set (WifiConfiguration.AuthAlgorithm.SHARED);

        wc.allowedGroupCiphers.set   (WifiConfiguration.GroupCipher.WEP40);
        wc.allowedGroupCiphers.set   (WifiConfiguration.GroupCipher.WEP104);

        wc.allowedKeyManagement.set  (WifiConfiguration.KeyMgmt.NONE);

        wc.allowedPairwiseCiphers.set (WifiConfiguration.PairwiseCipher.TKIP);
        wc.allowedPairwiseCiphers.set (WifiConfiguration.PairwiseCipher.CCMP);

        wc.allowedProtocols.set      (WifiConfiguration.Protocol.WPA);
        wc.allowedProtocols.set      (WifiConfiguration.Protocol.RSN);

        wc.hiddenSSID                = false;
        wc.priority                  = 32;

        wc.SSID                      = "\"" + SSID + "\"";
        wc.status                    = WifiConfiguration.Status.ENABLED;

        wc.wepKeys[0]                = key;
        wc.wepTxKeyIndex             = 0;

        int netID;                   
        if (-1 == (netID             = wifiMgr.addNetwork (wc)))
        {
            listener.lostConnection (true);
        }
        else
        {
            wifiMgr.enableNetwork (netID, true);
            Thread.sleep (5000);  // Delay to allow the DHCP process to work
        }
    }
    catch (Exception e)
    {
        listener.lostConnection (true);
    }
}

It should be pointed out that I always use the same wireless access point, and the code in joinNetwork() is specifically configured for it, so if your configuration needs to be more flexible, then your solution may be more complex. Sadly, I do not remember the web site where I found the starting point for this code, but it didn't take a ton of Googling to find it. Finally, I'm pretty sure your application needs to have the ACCESS_WIFI_STATE and CHANGE_WIFI_STATE permissions.

3
  • Thanks Rich, but your answer seems to be a bit irrelevant for my problem. I don't really need my app to connect to the network, it just has to check the network's state. My problem is that sometimes the method that I use returns false result.
    – user519908
    Dec 2, 2010 at 11:08
  • I understand, and I needed the same thing for my app. It may be that I'm taking an overly detailed look, but my code first verifies the existence of the WiFi connection, then its state, then its connection, then its configuration, all of which has been very reliable in determining whether I've got network functionality without relying on isConnected() -- which doesn't always work for you. I believe that you could adapt this process for your needs and avoid the problems you've been having with isConnected()...
    – Rich
    Dec 2, 2010 at 18:10
  • Also, I found this web page to be very helpful in figuring out how to work with my Android wifi connection: kmansoft.wordpress.com/2010/04/08/…
    – Rich
    Dec 2, 2010 at 18:11
0

I use code like this:

public static String getCurrentSsid(Context context) {
  final WifiInfo wifiInfo = getCurrentWifiInfo(context);
  if (wifiInfo != null && !StringUtil.isBlank(wifiInfo.getSSID())) {
    return wifiInfo.getSSID();
  }
  return null;
}

public static WifiInfo getCurrentWifiInfo(Context context) {
  final ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  final NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  if (networkInfo != null && networkInfo.isConnected()) {
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    return wifiManager.getConnectionInfo();
  }

  return null;
}

At the same time be aware of this two issues 19078 and 3641.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.