今天来点干货,讲讲如何通过代码连接上指定的wifi。相当于使用代码完成使用者在手机WLAN中选择wifi,并且输入密码,然后点击确定的过程。
既然要操纵wifi,就需要使用到wifiManager,我们连接过的wifi的名称和密码都可以通过WifiManger来拿到,每个信息都是封装到一个ScanResult的类中,然后放到列表中的。
WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
1 如何获取已经连接过的wifi信息
mWifiManager.startScan(); mWifiList = mWifiManager.getScanResults(); mWificonfiguration = mWifiManager.getConfiguredNetworks();
2 去连接以前连接过的wifi
mWifiManager.enableNetwork(index, true); 其中的index是netWorkId,就是存在上面的list(mWificonfiguration)中的,目前获取networkId只能去列表中获取。
3获取networkId
int networkId = mWificonfiguration.get(index).networkId; 其中的index,需要自己确定
4上面都是讲的连接以前连过的,现在说如何连接从来没有连接过的wifi.上面都是从列表信息中拿到了networkId,现在从来没有连接过的wifi怎么获取networId呢?我们可以创建一个wifi的信息,然后添加到wifiManager中去,然后再获取networkId,就ok了。
public WifiConfiguration createWifiInfo(String SSID, String Password, int Type) { WifiConfiguration configuration = new WifiConfiguration(); configuration.allowedAuthAlgorithms.clear(); configuration.allowedGroupCiphers.clear(); configuration.allowedKeyManagement.clear(); configuration.allowedPairwiseCiphers.clear(); configuration.allowedProtocols.clear(); configuration.SSID = "\"" + SSID + "\""; WifiConfiguration tempConfig = this.isExsits(SSID); if(tempConfig != null) { mWifiManager.removeNetwork(tempConfig.networkId); } switch (Type) { case 1://不加密 configuration.wepKeys[0] = ""; configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); configuration.wepTxKeyIndex = 0; configuration.priority= 20000; break; case 2://wep加密 configuration.hiddenSSID = true; configuration.wepKeys[0] = "\"" + Password +"\""; configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); break; case 3: //wpa加密 configuration.preSharedKey = "\"" + Password + "\""; configuration.hiddenSSID = true; configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); configuration.status = WifiConfiguration.Status.ENABLED; break; } return configuration; } 上面是创建wifi配置信息,下面是添加 int networkId = mWifiManager.addNetwork(wifiConfiguration);
比如关掉wifi这一类的方法我也就不在这里多说了,上面的方法我已经封装成了工具类。
源码地址:https://github.com/Blowing/AutoConnectWifi
你的支持,是我坚持的动力,如果觉得有用,请点个赞。谢谢!