项目开发中经常会用到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);
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。