Android 监听网络状态变化(无切换中间态版)
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
class NetworkStateReceiver(private val networkStateChangeListener: NetworkStateChangeListener) : BroadcastReceiver() {
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
networkStateChangeListener.onNetworkAvailable()
}
override fun onLosing(network: Network, maxMsToComplete: Int) {
super.onLosing(network, maxMsToComplete)
networkStateChangeListener.onNetworkLosing()
}
override fun onLost(network: Network) {
super.onLost(network)
networkStateChangeListener.onNetworkLost()
}
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities)
networkStateChangeListener.onNetworkCapabilitiesChanged()
}
}
fun register(context: Context) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkRequest = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
}
fun unregister(context: Context) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.unregisterNetworkCallback(networkCallback)
}
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
networkStateChangeListener.onNetworkStateChange()
}
}
interface NetworkStateChangeListener {
fun onNetworkAvailable()
fun onNetworkLosing()
fun onNetworkLost()
fun onNetworkCapabilitiesChanged()
fun onNetworkStateChange()
}
}
使用方法:
- 创建\`Network
评论已关闭