代码改变世界

[Network] 判断设备是否能访问 Internet

2021-02-10 15:44  shaobin0604  阅读(385)  评论(0编辑  收藏  举报

Android API Level 21 新增 API android.net.NetworkCapabilities

判断是否能访问 Internet

val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)

return networkCapabilities != null
           && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
           && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)

参考