码迷,mamicode.com
首页 > 其他好文 > 详细

WiFi有密码和无密码连接

时间:2014-06-28 00:13:28      阅读:418      评论:0      收藏:0      [点我收藏+]

标签: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

WiFi有密码和无密码连接,布布扣,bubuko.com

WiFi有密码和无密码连接

标签:wifi 连接 密码

原文地址:http://670176656.blog.51cto.com/4500575/1431554

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!