首页 > 代码库 > WiFi有密码和无密码连接
WiFi有密码和无密码连接
项目开发中经常会用到Wifi连接
Wifi连接分两种情况有密码和无密码
一下两种方法分别是连接有密码和无密码的方法
经过小米2S和三星平板验证
//连接有密码的Wifi
private void connectToWifi(String SSID, String key) {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + SSID + "\""; // wifi名称
wc.preSharedKey = "\"" + key + "\""; // wifi密码
wc.hiddenSSID = true;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int res = wifi.addNetwork(wc);
boolean b = wifi.enableNetwork(res, false);
}
//连接无密码的Wifi
// 连接Wifi
private void connectToWifi(String SSID) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
//这个好像不太稳定,之前可以连接有密码的,现在又不行了,不清楚是什么原因
// config.wepKeys[0] = password; // 这里要注释掉 因为连接的是没有密码的Wifi
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
wifiManager.enableNetwork(wifiManager.addNetwork(config), true);
}
本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1431554