本示例连接到具有WPA2加密的Wi-Fi接入点。
public boolean ConnectToNetworkWPA(String networkSSID, String password) { try { WifiConfiguration conf = new WifiConfiguration(); conf.SSID= "\"" + networkSSID + "\""; //请注意引号。字符串应在引号中包含SSID conf.preSharedKey= "\"" + password + "\""; 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); Log.d("connecting",conf.SSID+ " " + conf.preSharedKey); WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiManager.addNetwork(conf); Log.d("after connecting",conf.SSID+ " " + conf.preSharedKey); List<WifiConfiguration> list = wifiManager.getConfiguredNetworks(); for( WifiConfiguration i : list ) { if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) { wifiManager.disconnect(); wifiManager.enableNetwork(i.networkId, true); wifiManager.reconnect(); Log.d("re connecting",i.SSID+ " " + conf.preSharedKey); break; } } //WiFi连接成功,返回true return true; } catch (Exception ex) { System.out.println(Arrays.toString(ex.getStackTrace())); return false; } }