概述:上层开发者想要通过代码来连接wifi,那么离不开wifimanager和WifiConfiguration.
思想就是通过构造WifiConfiguration的各项参数,封装成对象之后调用wifimanager的enableNetwork接口去连接wifi网络。
到达wifimanager之后就是走系统层wifi 的连接处理流程。
在连接的流程中就包含密码的存储等操作,关于wifi密码的存储是在data\misc\wifi\wpa_supplicant.conf中的。
整个wpa_supplicant就是wifi的驱动层,这块就比较复杂了。不是这里要说的重点。
言归正传,app连接的具体代码如下:
连接带密码的
public boolean connectWifiPassword(WifiManager mWifiManager, String SSID, String Password) {
Log.e("NetworkFragment", "setWifiParamsPassword");
removeWifi(mWifiManager, SSID);
WifiConfiguration configuration = new WifiConfiguration();
configuration.SSID = "\"" + SSID + "\"";
configuration.preSharedKey = "\"" + Password + "\"";
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.RSN);
configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
configuration.status = WifiConfiguration.Status.ENABLED;
return mWifiManager.enableNetwork(mWifiManager.addNetwork(configuration), true);
}
不带密码的
public boolean connectWifiNoPassword(WifiManager mWifiManager, String ssid) {
removeWifi(mWifiManager, ssid);
WifiConfiguration configuration = new WifiConfiguration();
configuration.SSID = "\"" + ssid + "\"";
configuration.status = WifiConfiguration.Status.ENABLED;
configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
configuration.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
configuration.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
return mWifiManager.enableNetwork(mWifiManager.addNetwork(configuration), true);
}
获取wifi的加密类型
public String getEncryptionType(ScanResult scanResult) {
if (!TextUtils.isEmpty(scanResult.SSID)) {
String capabilities = scanResult.capabilities;
Log.i(TAG, "[" + scanResult.SSID + "]" + capabilities);
if (!TextUtils.isEmpty(capabilities)) {
if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
return "wpa";
} else if (capabilities.contains("WEP")
|| capabilities.contains("wep")) {
return "wep";
} else {
return "";
}
}
}
return scanResult.capabilities.toString();
}
另外,如果想要修改wifi重连的次数的话,需要修改系统代码。
frameworks\opt\net\wifi\service\java\com\android\server\wifi\SupplicantStateTracker.java
/* Maximum retries on a authentication failure notification */
private static final int MAX_RETRIES_ON_AUTHENTICATION_FAILURE = 2;
/* Maximum retries on assoc rejection events */
private static final int MAX_RETRIES_ON_ASSOCIATION_REJECT = 16;
以上便可在自己的app中通过自己定义密码完美的实现wifi的连接。
更多精彩文章,请关注如下二维码对应公众号“代码视觉”。转载请联系授权!
代码视觉
网友评论