2011-03-10 112 views
5

这是杀了我,任何帮助将不胜感激。Android的wifimanager总是返回true

我想连接到使用wifi管理器的开放网络。我遇到的问题是代码声称连接到任何网络 - 甚至不存在的网络。下面是整个代码被执行并被网络的SSID调用。即使没有任何形状或形式的网络存在,您传递给网络的SSID也不重要,enableNetwork声明返回true,我相信这意味着它连接到网络。

我需要做的是确保我有连接。所以如果我传递一个不存在的网络SSID(例如,它超出范围),API尝试连接时应该返回失败。

任何想法/提示/建议将不胜感激。

public boolean conto (String network){ 

    WifiConfiguration wifiConfiguration = new WifiConfiguration(); 
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
    List<WifiConfiguration> configs = null; 
    int inetId = -1; 


    // make sure there are no funny stuff in the config 
    configs = wifi.getConfiguredNetworks(); 
    for (WifiConfiguration config : configs) { 
     wifi.removeNetwork(config.networkId); 
     Log.d("********", "Removed Network: SSID=[" + config.SSID + "] and ID=[" + config.networkId + "]"); 

    } 

    // Now add the network 
    wifiConfiguration.SSID = "\"" + network + "\""; 
    wifiConfiguration.hiddenSSID = false; 
    //wifiConfiguration.priority = 1; 
    //wifiConfiguration.networkId = 999; 

    inetId = wifi.addNetwork(wifiConfiguration); 
    if(inetId < 0) { 
      Log.d("********", "Could Not Add Network......... [" + wifiConfiguration.SSID + "]"); 

     } 
     else { 

      Log.d("********", "Added Network......... [" + wifiConfiguration.SSID + "]"); 

      // Lets be paranoid and double check the config file 
      Log.d("********", " +++++++++++++++++++++++++ This is what I have in Config File"); 
      configs = wifi.getConfiguredNetworks(); 
      for (WifiConfiguration config : configs) { 
       Log.d("********", "In the Config file after add, SSID=[" + config.SSID + "], ID=[" + config.networkId + "]"); 

      } 

      // Now Enable the network 
      boolean successConnected = wifi.enableNetwork(inetId, true); 
      //boolean successAssociated = wifi.reassociate(); This did not change the results 

      if(successConnected) { 
       Log.d("********", "Connected to......... [" + inetId + "]"); 
      } 
      else { 

       Log.d("********", "Could Not Connect to......... [" + inetId + "]"); 

      } 


     } 
     return false; 
    } 
+0

你有没有解决这个问题?我有[同样的问题](http://stackoverflow.com/questions/11378452/android-wifimanager-making-a-phantom-connection)。 – gcl1 2012-07-08 00:03:43

回答

9

我认为问题在于你的代码是基于这样的假设:连接到WiFi网络是一个同步过程,事实并非如此。方法enableNetwork()在连接发生时不会阻塞,然后返回连接的成功或失败,它会立即返回,结果就是请求是否正确地到达了WiFi服务和请求方。

如果您想要了解设备连接状态的情况,则需要使用BroadcastReceiver监控WifiManager. SUPPLICANT_STATE_CHANGED_ACTIONWifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION广播意图操作。一旦你启动连接过程,这些回调将告诉你事情的进展。例如,如果您通过一个不存在的网络,连接状态应该立即直接进入DISCONNECTED状态。虽然有效的网络将经历关联,认证和连接的过程。所有这些步骤都通过这些广播进行列举。