(Android开发)WiFi无密码保护时连接不上

在开发WiFi功能时,在网上找到的大多连接方式都是下面这样,需要密码时这样没问题,但是遇到无密码保护的WiFi就连接不上了:
private WifiConfiguration createConfiguration(AccessPoint ap) {
		String SSID = ap.getSsid();
                String BSSID = ap.getBssid();
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
                // SSID要加双引号,而BSSID不加双引号,否则连接失败
		config.SSID = "\"" + SSID + "\""; 
                config.BSSID = BSSID; 
		String encryptionType = ap.getEncryptionType();
		String password = ap.getPassword();
		Log.d(TAG, "createConfiguration: SSID = " + SSID + ", password = " + password + ", encryptionType = " + encryptionType);
		if (encryptionType.contains("wep")) {
			int i = password.length();
			if (((i == 10 || (i == 26) || (i == 58))) && (password.matches("[0-9A-Fa-f]*"))) {
				config.wepKeys[0] = password;
			} else {
				config.wepKeys[0] = "\"" + password + "\"";
			}
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		} else if (encryptionType.contains("wpa")) {
			config.preSharedKey = "\"" + password + "\"";
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
		} else {
			config.wepKeys[0] = "";
			config.wepTxKeyIndex = 0;
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
		}
		return config;
	}

其实只要把下面两句不要,注释掉就可以了

config.wepKeys[0] = "";
config.wepTxKeyIndex = 0;

网上的demo加上这两个都是误导,找了半天才找到,记录下。

另外要添加BSSID时不需要加双引号,而SSID要加双引号,否则会导致连接失败

config.SSID = "\"" + SSID + "\"";
config.BSSID = BSSID;

你可能感兴趣的:((Android开发)WiFi无密码保护时连接不上)