Android网络状态监听

1.添加权限

    

2.获取ConnectivityManager

val connectivityManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    application.getSystemService(ConnectivityManager::class.java) ?: null
                } else {
                    application.getSystemService(Context.CONNECTIVITY_SERVICE)?.let {
                        it as ConnectivityManager
                    }
                }

3监听网络状态

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//大于Android N的版本

     val networkRequest = NetworkRequest.Builder()
                        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
                        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                        .build()
     connectivityManager?.registerNetworkCallback(networkRequest, object :
           ConnectivityManager.NetworkCallback() {
                 override fun onAvailable(network: Network) {//有可用网络
                     super.onAvailable(network)
                    val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
                            networkCapabilities?.let {
                              //获取网络类型
                                val isWIFI = it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
                                val isMobile = it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
                             
                        }

                        override fun onLost(network: Network) {
                            super.onLost(network)
                           //网络断开

                        }

                        override fun onUnavailable() {
                            super.onUnavailable()
                            //无可用网络
                            
                        }
                    })
                } else {//Android N以下通过广播监听
                   
                    val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
                    application.registerReceiver(NetworkStateReceiver(), intentFilter)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
  • 网络监听广播
 class NetworkStateReceiver : BroadcastReceiver() {
     override fun onReceive(context: Context?, intent: Intent?) {
         context?.getSystemService(Context.CONNECTIVITY_SERVICE)?.let {
                val cm = it as ConnectivityManager
                cm.activeNetworkInfo?.let { networkInfo ->
                    networkInfo.type//网络类型
                    networkInfo.isConnected//是否连接
                }
            }
     }

}

你可能感兴趣的:(Android网络状态监听)