问题:Android的isConnected()用于获取WiFi的当前状态,即使连接设备也经常返回false

时间:2010-12-01 13:48:26

标签: android connection wifi

我的Android应用只能在连接到互联网的WiFi上运行。因此,我使用以下代码检查设备是否已连接:

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

但是,通常在启动应用程序并将WiFi连接到Internet时,我会收到仅在wifi = false时显示的通知。我错过了什么,或者支票不准确吗?

2 个答案:

答案 0 :(得分:2)

我的项目也依赖于Wifi(虽然我使用私人网络)。以下是我在启动时设置Wifi连接的代码:

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);
    }
}

应该指出的是,我总是使用相同的无线接入点,并且joinNetwork()中的代码是专门为它配置的,因此如果您的配置需要更加灵活,那么您的解决方案可能会更复杂。可悲的是,我不记得我找到这个代码的起点的网站,但它并没有花费大量的谷歌搜索来找到它。最后,我非常确定您的应用程序需要具有ACCESS_WIFI_STATE和CHANGE_WIFI_STATE权限。

答案 1 :(得分:0)

我使用这样的代码:

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;
}

同时请注意这两个问题190783641