我可以使用以下代码连接特定网络。但我想通过使用SSID,安全选项和密码来添加网络。
public void connectToSelectedNetwork(WifiManager wifiManager, String networkSSID, String password, boolean open_secured) {
try {
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + networkSSID + "\"";
if (!open_secured)
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
else {
wifiConfig.preSharedKey = "\"" + password + "\"";
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
}
// WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
// int netId = wifiManager.addNetwork(wifiConfig);
int netID = wifiManager.addNetwork(wifiConfig);
if (wifiConfig.SSID != null && wifiConfig.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(netID, true);
wifiManager.saveConfiguration();
wifiManager.reconnect();
}
// Toast.makeText(SettingsActivity.this,"position "+position+" "+netID,Toast.LENGTH_LONG).show();
// PreviousNetworkID.add(position,netID);
} catch (Exception e) {
e.printStackTrace();
System.out.println("logs " + e.toString());
}
}