项目场景:
需要获取当前网络状态,如果是wifi还要获取wifi名称
解决方案:
/**
*获取网络状态的类型
*/
fun checkNetworkType(ctx: Context): Int {
val context=ctx.applicationContext
val netType=0
val manager= ContextCompat.getSystemService(context, ConnectivityManager::class.java) ?: return netType
val networkInfo =manager.activeNetworkInfo ?: return netType
return when (networkInfo.type) {
ConnectivityManager.TYPE_WIFI, ConnectivityManager.TYPE_WIMAX, ConnectivityManager.TYPE_ETHERNET -> 1
ConnectivityManager.TYPE_MOBILE -> when (networkInfo.subtype) {
TelephonyManager.NETWORK_TYPE_LTE // 4G
, TelephonyManager.NETWORK_TYPE_HSPAP, TelephonyManager.NETWORK_TYPE_EHRPD -> 2
TelephonyManager.NETWORK_TYPE_UMTS // 3G
, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_EVDO_B -> 2
TelephonyManager.NETWORK_TYPE_GPRS // 2G
, TelephonyManager.NETWORK_TYPE_EDGE -> 2
else -> netType
}
else -> netType
}
}
fun checkNetworkTypeStr(ctx: Context): String {
return when (checkNetworkType(ctx)) {
1 -> "无线网络"
2 -> "移动网络"
else -> "网络错误"
}
}
var netName=""
val wifiManager:WifiManager=applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
var wifiName=wifiManager.connectionInfo.ssid
if (wifiName.contains("\"")) {
wifiName = wifiName.substring(1, wifiName.length - 1)
}
//在所用的activity里使用上面的方法
when(NetWorkUtils().checkNetworkTypeStr(this)){
"移动网络"->netName="移动网络"
"网络错误"->netname="网络错误"
"无线网络"->netName=wifiName
}
//现在获取网络状态都需要定位权限
if (netName=="<unknown ssid>"){
netName="请开启定位,确认wifi"
}