最近遇到一个奇怪的bug,部分手机上获取wifi的名字,通过
WifiManager.getConnectionInfo().getSSID()
为"unknown ssid"
,调试查看SSID为""
,这导致接下来的一系列逻辑都出现了问题。目前发现RROS(Remix)的ROM会出现这个问题。特此记录解决方法。
首先实例化WifiManager和ConnectivityManager
fun init(context: Context) {
if (sWifiManager == null) {
sWifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
}
if (sConnManger == null) {
sConnManger = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
}
}
方式一:通过WifiManager.getConnectionInfo().getSSID()
方式二:通过ConnectivityManager.getNetworkInfo().getExtraInfo()
方式三:通过匹配已保存的网络WifiManager.getConfiguredNetworks()
代码如下:
fun getCurrWifiName(): String {
val info = sWifiManager?.connectionInfo ?: return NONE
val ssid = if (info.ssid == null) null else info.ssid.replace("\"", "")
if (isSSIDEmpty(ssid)) {
if (sConnManger == null) {
return NONE
}
val network = sConnManger!!.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
?: return NONE
var wifiName = network.extraInfo
if (!TextUtils.isEmpty(wifiName)) {
if (wifiName.startsWith("\"")) {
wifiName = wifiName.substring(1)
}
if (wifiName.endsWith("\"")) {
wifiName = wifiName.substring(0, wifiName.length - 1)
}
return wifiName
} else {
val networkId = info.networkId
val configuredNetworks = sWifiManager!!.configuredNetworks
if (configuredNetworks != null) {
for (wifiConfiguration in configuredNetworks) {
if (wifiConfiguration.networkId == networkId) {
return wifiConfiguration.SSID
}
}
}
}
}
return if (isSSIDEmpty(ssid)) NONE else ssid!!
}
private fun isSSIDEmpty(ssid: String?): Boolean {
return ssid == null || ssid == "<unknown ssid>" || ssid == "0x"
}
9.0及以上的机型,必须打开位置权限的总开关,并且请求定位权限,才可以正确获取到WIFI名称