Android 13 监控网络连接状态

Android 13 监控网络连接状态

获取瞬时状态

1
2
3
4
5
6
val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val currentNetwork = cm.activeNetwork
if (currentNetwork != null) {
val caps = cm.getNetworkCapabilities(currentNetwork)
val linkProperties = cm.getLinkProperties(currentNetwork)
}

监听网络事件

NetworkCallback 类与 ConnectivityManager.registerDefaultNetworkCallback(NetworkCallback)ConnectivityManager.registerNetworkCallback(NetworkCallback) 结合使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
cm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
Log.e(TAG, "The default network is now: " + network)
}

override fun onLost(network: Network) {
Log.e(TAG, "The application no longer has a default network. The last default network was " + network)
handle(null)
}

override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
Log.d(TAG, "The default network changed capabilities: " + networkCapabilities)
handle(networkCapabilities)
}

override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
Log.i(TAG, "The default network changed link properties: " + linkProperties)
}
})

解析NetworkCapabilities的网络状态信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 private fun handle(caps: NetworkCapabilities?) {
if (caps != null) {
if (caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
if (
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE)
) {
setResult(STATE_WIFI)
return
} else if (
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
) {
setResult(STATE_MOBILE)
return
}
}
}
setResult(STATE_UNKNOWN)
return
}
作者

Dench

发布于

2023-01-31

更新于

2023-01-31

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×