15

我使用下面的代码连接到加密网络。但是,如果网络不安全并且我将密钥留空(“”),那么它就会失败。有谁知道如何解决这个问题?此外,是否可以使用 ssid / bssid 检测网络是否打开?还是我必须使用过滤器进行扫描?

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

1 回答 1

14

利用

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

只有,它会工作。

删除所有其他分配wc,不必将它们用于连接到网络的简单任务。你不是creating一个网络,你正在连接一个网络existing

有关完整解决方案,请查看此链接:如何以编程方式连接到 Android 中的特定 Wi-Fi 网络? 它有你需要知道的一切。

于 2012-10-19T06:36:37.300 回答