2012-10-08 18 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

* ssidのみから暗号化方法を取得する方法についてのコードはありますか? – bluewhile

+2

いいえ暗号化方法がssidからのみ見つかりません。ネットワークをスキャンしてScanResultを使用して、使用可能なすべてのネットワークを取得する必要があります。次に、指定されたssidを使用してネットワークを検索し、暗号化方式を見つけます。リンクはhttp://stackoverflow.com/a/12747455/1117338とhttp://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilitiesです –

関連する問題