赞
踩
Android设备网络监听,是否连接和连接状态判断:
关键类:
object NetworkStateUtils { /** * 判断当前设备是否有网络连接 */ fun hasNetworkCapability(context: Context): Boolean { try { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val activeNetwork = connectivityManager?.activeNetwork ?: return false val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) } else { val networkInfo = connectivityManager?.activeNetworkInfo ?: return false return networkInfo.isAvailable && networkInfo.isConnected } } catch (e: Exception) { e.printStackTrace() } return false } /** * 获取当前网络状态 */ fun getNetworkState(context: Context?): NetworkState { try { val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val activeNetwork = connectivityManager?.activeNetwork ?: return NetworkState.NONE val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return NetworkState.NONE return when { networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> NetworkState.WIFI networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> NetworkState.CELLULAR networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> NetworkState.ETHERNET else -> NetworkState.NONE } } else { return when (connectivityManager?.activeNetworkInfo?.type) { ConnectivityManager.TYPE_MOBILE -> NetworkState.CELLULAR ConnectivityManager.TYPE_WIFI -> NetworkState.WIFI ConnectivityManager.TYPE_ETHERNET -> NetworkState.ETHERNET else -> NetworkState.NONE } } } catch (e: Exception) { e.printStackTrace() } return NetworkState.NONE } }
参考:
https://blog.csdn.net/SweetTool/article/details/105377697
https://github.com/kongqw/NetworkMonitor
com.test.util.NetworkUtil
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。