Android Q 检查网络连通性

对Android Q 上检查网络连通性的相关记录


前言

大多数情况下,我们从ConnectivityManager获取活动的网络信息,并检查该网络是否已经连接

像这样

1
2
3
4
5
fun isNetworkConnected(context: Context?): Boolean {
val mConnectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mNetworkInfo = mConnectivityManager.activeNetworkInfo
return mNetworkInfo!=null && mNetworkInfo.isConnected
}

但是在Android Q (API 29) 上,从ConnectivityManager类里废弃activeNetworkInfo方法(Java对应getActiveNetworkInfo()方法)。

Android Q

查询相关文档,可以找到另一种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fun isNetworkConnectedWithQ(context: Context?): Boolean {

var hasNetwork = false
if (context != null) {
val mConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networks = mConnectivityManager.allNetworks
if (networks.isNotEmpty()) {
for (network in networks) {
val nc = mConnectivityManager.getNetworkCapabilities(network)
if (nc!!.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
hasNetwork = true
}
}
}

}

return hasNetwork
}

注意:以上代码中allNetworksgetNetworkCapabilitieshasCapability都是在API 21 (Lollipop)被添加的,也就是说最低版本需要21。对此,这里为了兼容到21版本以下,可以将两种方式合并到一个方法中,同时兼容。

同时兼容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fun isNetworkConnected(context: Context?): Boolean {

val mConnectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

if (Build.VERSION.SDK_INT<Build.VERSION_CODES.Q){
val mNetworkInfo = mConnectivityManager.activeNetworkInfo
return mNetworkInfo!=null && mNetworkInfo.isConnected
}

var hasNetwork = false

val networks = mConnectivityManager.allNetworks
if (networks.isNotEmpty()) {
for (network in networks) {
val nc = mConnectivityManager.getNetworkCapabilities(network)
if (nc!!.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
hasNetwork = true
}
}
}

return hasNetwork

}

最后,不要忘记在清单文件添加网络权限

1
2

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

以上就是针对Android Q上网络检查方式的一个简单的记录,如有不足,欢迎指正

0%