目录
第一步:连接指定WIFI
连接硬件设备暴露出来的Wifi,Wifi名称都应该有规定的格式。
连接指定Wifi前,自己需要组装好 WifiConfiguration
//WIFI密码类型
const val WIFICIPHER_WPA = 0
const val WIFICIPHER_WEP = 1
const val WIFICIPHER_NOPASS = 2
/**
* 创建新的WIFI连接对象 WifiConfiguration
* type Wifi的密码类型
*/
fun createWifiInfo(SSID: String, password: String,
type: Int) : WifiConfiguration{
val config = WifiConfiguration()
config.allowedAuthAlgorithms.clear()
config.allowedGroupCiphers.clear()
config.allowedKeyManagement.clear()
config.allowedPairwiseCiphers.clear()
config.allowedProtocols.clear()
config.SSID = "\"" + SSID + "\""
when (type) {
Constant.WIFICIPHER_NOPASS -> {
config.wepKeys[0] = "\"" + "\""
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
config.wepTxKeyIndex = 0
}
Constant.WIFICIPHER_WEP -> {
config.preSharedKey = "\"" + password + "\""
config.hiddenSSID = true
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED)
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.CCMP)
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.TKIP)
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP40)
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104)
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
config.wepTxKeyIndex = 0
}
Constant.WIFICIPHER_WPA -> {
config.preSharedKey = "\"" + password + "\""
config.hiddenSSID = true
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN)
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.TKIP)
config.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.WPA_PSK)
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP)
// config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.CCMP)
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP)
config.status = WifiConfiguration.Status.ENABLED
}
}
return config
}
使用config连接Wifi
/**
* 连接指定Wifi
*/
private fun connectWifi(name: String, config: WifiConfiguration) {
//判断当前系统是否已经缓存有和 name相同的wifi
var isCon = false
//遍历当前系统所有保存的Wifi
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
for (c in wifiManager.configuredNetworks) {
//注意这里名字里面还有""
if (c.SSID.toString() == "\"$name\"") {
isCon = true
//如果有保存过的wifi,直接调用连接
WiFiUtil().connectWifiByReflectMethod(c.networkId, wifiManager, config)
}
}
if (!isCon) {
//如果没有需要自己构建config连接wifi
connect(config)
}
}
/**
* 连接自己创建的Wifi
*/
private fun connect(config: WifiConfiguration) {
//获取构建好的WifiConfig的ID
val wcgID = wifiManager.addNetwork(config)
//重点。使用反射调用各版本系