2013-11-02 46 views
3

试图以编程方式从Android连接到我的无线网络。以编程方式连接到Android中的WPA/WPA2 PSK

安全类型是WPA2,加密AES。

private WifiConfiguration saveWepConfig(String password, String networkSSID) { 
     WifiConfiguration conf = new WifiConfiguration(); 
     conf.SSID = "\"" + networkSSID + "\""; 
     // conf.wepKeys[0] = "\"" + password + "\""; 
     conf.preSharedKey = "\"" + password + "\""; 
     conf.wepTxKeyIndex = 0; 
      conf.hiddenSSID = true; 
     conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 
     conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
     return conf; 
    } 

我是不是要在这里加密密码:

预期这不起作用?它只保存连接,不连接。

回答

5

啊...我找到了解决办法之后我张贴的问题:

WifiConfiguration conf = new WifiConfiguration(); 
     conf.SSID = "\"" + networkSSID + "\""; 
     conf.preSharedKey = "\"" + password + "\""; 
//  conf.hiddenSSID = true; 
//  conf.wepTxKeyIndex = 0; 
//  conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 
//  conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 

     conf.status = WifiConfiguration.Status.ENABLED;   
     conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 
     conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 
     conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 
     conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 
     conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 
     conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); 

它为我工作。 谢谢。

+0

这不会将您连接到WPA2-PSK(AES),是吗? – Ben

+0

也适用于我。日Thnx。 – msamardzic

2

您只需要设置SSIDpreSharedKey。其他所有内容默认为WPA/WPA2(对于真正的旧版Android,可能并非如此)。

public static void saveWpaConfig(Context context, String ssid, String passphrase) 
{ 
    WifiConfiguration wifiConfiguration = new WifiConfiguration(); 
    wifiConfiguration.SSID = "\"" + ssid + "\""; 
    wifiConfiguration.preSharedKey = "\"" + passphrase + "\""; 

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
    int networkId = wifiManager.addNetwork(wifiConfiguration); 
    if (networkId != -1) 
    { 
     wifiManager.enableNetwork(networkId, true); 
     // Use this to permanently save this network 
     // Otherwise, it will disappear after a reboot 
     wifiManager.saveConfiguration(); 
    } 
}