Android 登录已知wifi

来源:互联网 发布:spring session源码 编辑:程序博客网 时间:2024/04/30 03:25

最近有个需求,开机之后想让用户登录到某个已知的wifi,而不用用户手动输入密码。前提是我们周围有这个wifi,而且知道这个wifi的密码。找了很多资料,最后发现下面几行代码就可以实现了。先写下了也算收藏了。


String user = "test";
String pwd = "
12345678";

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + user + "\"";
wc.preSharedKey = "\"" + pwd + "\"";
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);
Log.e("WifiPreference", "add Network returned " + res );
boolean b = wifi.enableNetwork(res, true);
Log.e("WifiPreference", "enableNetwork returned " + b );


自己创建个工程,复制粘贴就ok了

0 0