WIFI连接过程大致为:
打开WIFI模块-------->开始扫描-------->扫描到需连接WIFI名将配置信息保存-------->开始进行连接--------->连接完成
对应的代码大致为:
setWifiEnabled(true)-------->startScan()-------->收到SCAN_RESULTS_AVAILABLE_ACTION消息开始扫描-------->将WifiConfiguration保存并addNetwork(configuration)添加
-------->扫描结束enableNetwork(res, true)开始尝试连接-------->收到NETWORK_STATE_CHANGED_ACTION消息判断此时WIFI是否已真正连接
-------->WIFI已连接-------->结束
在此过程当中有几点需特别注意
1.将WifiConfiguration保存
因为WIFI的配置信息变化很多,比如有密码和没密码,有密码的加密方式也各不一样,所以在你想连WIFI之前一定要确定路由的配置,这样才能做到有的放矢,笔者只用到了两种方式:(1)无密码(2)有密码且为WPA/WPA2加密方式,代码为
if (mKey == null) {//无密码
configuration.allowedAuthAlgorithms.clear();
configuration.allowedGroupCiphers.clear();
configuration.allowedKeyManagement.clear();
configuration.allowedPairwiseCiphers.clear();
configuration.allowedProtocols.clear();
configuration.SSID = "\"" + mSSID + "\"";
configuration.wepKeys[0] = "";
configuration.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.NONE);
configuration.wepTxKeyIndex = 0;
res = mWifiManager.addNetwork(configuration);
mWifiManager.saveConfiguration();
} else {//有密码且为WPA/WPA2加密方式
configuration.SSID = "\"" + mSSID + "\"";
configuration.preSharedKey = "\"" + mKey + "\""; // 该热点的密码
configuration.hiddenSSID = true;
configuration.status = WifiConfiguration.Status.ENABLED;
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.TKIP);
configuration.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
configuration.allowedProtocols
.set(WifiConfiguration.Protocol.WPA);
res = mWifiManager.addNetwork(configuration);
mWifiManager.saveConfiguration();
}
2.如何知道WIFI是否已连接上
(1)enableNetwork(res, true)的返回值只是这个函数是否执行成功,不代表是否已连上WIFI
(2)收到NETWORK_STATE_CHANGED_ACTION消息的情况有多种 未连接---------->已连接 未连接/已连接 ---------->WIFI关闭
所以在收到 NETWORK_STATE_CHANGED_ACTION之后需判断WIFI是否已真正连接上,判断方法为
public boolean isWifiConnect() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = connManager.getActiveNetworkInfo();
return (ni != null && ni.isConnectedOrConnecting());
}
返回为true表示已连接,反之则未连接
3.很多之前已经连接上的WIFI,配置信息会自动保存,当你关闭---->打开WIFI时就会自动连接,但有时我们并不希望这样处理,
解决方法为在打开WIFI之前将以前所保存的信息清除,代码为
if(isWifiConnect()){
WifiInfo info = mWifiManager.getConnectionInfo();
mWifiManager.removeNetwork(info.getNetworkId());
mWifiManager.saveConfiguration();
}
此外,WIFI的信号强度即所谓的DB值是评判一个路由性能的标准,但很多人可能不知道其实它与我们通常所看到的格数之间是有4格标准和5各标准之说,
5格标准就是通常在产品右下角转态栏所看到的,对应关系为:
信号格数 | db值 |
0 | <=-89 |
1 | [-88,-78] |
2 | [-77,-67] |
3 | [-66, -56] |
4 | >=-55 |
4格标准就是设置或WIFI分析仪里所看到的,对应关系为:
信号格数 | db值 |
1 | <=-86 |
2 | [-85,-71] |
3 | [-70, -56] |
4 | >=-55 |