2012-10-08 71 views
13

我使用下面的代碼連接到加密的網絡。但是,如果一個網絡不安全,我把密鑰留空(「」),那麼它就會失敗。有沒有人有一個想法如何解決這個問題?此外,是否有可能使用ssid/bssid檢測網絡是否打開?或者我必須使用過濾器進行掃描?連接到開放WiFi

public void connectToSSID(final String ssid, final String key) { 
    Log.i("wifimaster", "connection to "+ssid); 

    WifiConfiguration wc = new WifiConfiguration(); 
    wc.SSID = "\""+ssid+"\""; //IMPORTANT! This should be in Quotes!! 
    wc.priority = 40; 
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); 
    wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); 
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); 
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); 
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 

    wc.preSharedKey = "\""+key+"\""; 
    wc.wepKeys[0] = "\""+key+"\""; //This is the WEP Password 
    wc.wepTxKeyIndex = 0; 

    wc.preSharedKey = "\""+key+"\""; 

    int res = wifiManager.addNetwork(wc); 
    Log.d("WifiPreference", "add Network returned " + res); 
    boolean es = wifiManager.saveConfiguration(); 
    Log.d("WifiPreference", "saveConfiguration returned " + es); 
    boolean b = wifiManager.enableNetwork(res, true); 
    Log.d("WifiPreference", "enableNetwork returned " + b); 

    if(b) 
     Toast.makeText(c, c.getString(R.string.connected), Toast.LENGTH_SHORT).show(); 
    else 
     Toast.makeText(c, c.getString(R.string.unconnected), Toast.LENGTH_SHORT).show(); 
} 

回答

12

使用

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

只是,它會工作。

刪除wc的所有其他任務,沒有必要將它們用於連接到網絡的簡單任務。你不是creating一個網絡,你連接到一個existing之一。

如需完整解決方案,請查看此鏈接:How do I connect to a specific Wi-Fi network in Android programmatically? 它包含了您需要知道的一切。

+0

你有沒有關於如何從* only * ssid獲取加密方法的代碼? – bluewhile

+2

不可以。只能從ssid找到加密方法。您必須掃描網絡,然後使用ScanResult獲取所有可用的網絡。然後用給定的ssid搜索你的網絡並找到它的加密方法。這裏是一個鏈接:http://stackoverflow.com/a/12747455/1117338和http://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities –