2011-03-10 82 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狀態。雖然有效的網絡將經歷關聯,認證和連接的過程。所有這些步驟都通過這些廣播進行列舉。