赞
踩
业务场景:
获取当前网络状态与类型
即提供两个方法,用于获取当前的网络状态、网络类型。
监听网络状态真正变化
网络状态真正变化,首先明确网络状态只有【有网】与【无网】,所以当 WIFI 和 数据流量 同时开启的情况下,仅关闭一项,不会提示网络状态的变更。
监听网络类型发生变化
网络类型发生变化,是指当前使用的网络类型发生变化。举个例子,WIFI、数据流量同时开启,理论上当前网络类型是 WIFI,所以当仅关闭 数据流量 时,不会提示网络类型变更,但仅关闭 WIFI 时,会提示网络类型变更为 数据流量。
这里还需要注意一点,有一个“系统默认网络”的概念:系统通常首选不按流量计费的网络而非按流量计费的网络,首选网速较快的网络而非网速较慢的网络。
常见监听网络状态有三种方式:
下面逐一实现看效果:
class NetConnectReceiver: BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Log.e("qingshan", "网络状态改变") context?.getSystemService(ConnectivityManager::class.java)?.allNetworkInfo?.filter { it.typeName == "MOBILE" || it.typeName == "WIFI" }?.forEach {networkInfo -> Log.e("qingshan", "${networkInfo?.typeName}, isConnect= ${networkInfo?.isConnected}") } } } //动态注册广播监听 class CustomApplication: Application() { override fun onCreate() { super.onCreate() //这里模拟工具类场景:全局一个监听,然后在工具类中分发。 registerReceiver(NetConnectReceiver(), IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) } }
2023-11-10 14:21:58.081 13917-13917 qingshan E 网络状态改变
2023-11-10 14:21:58.082 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:21:58.082 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:21:58.083 13917-13917 qingshan E 网络状态改变
2023-11-10 14:21:58.083 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:21:58.083 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:13:46.002 13917-13917 qingshan E 网络状态改变
2023-11-10 14:13:46.002 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:13:46.002 13917-13917 qingshan E WIFI, isConnect= true
2023-11-10 14:13:46.003 13917-13917 qingshan E 网络状态改变
2023-11-10 14:13:46.003 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:13:46.003 13917-13917 qingshan E WIFI, isConnect= true
2023-11-10 14:18:46.622 13917-13917 qingshan E 网络状态改变
2023-11-10 14:18:46.624 13917-13917 qingshan E MOBILE, isConnect= true
2023-11-10 14:18:46.624 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:18:46.624 13917-13917 qingshan E 网络状态改变
2023-11-10 14:18:46.624 13917-13917 qingshan E MOBILE, isConnect= true
2023-11-10 14:18:46.624 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:18:46.665 13917-13917 qingshan E 网络状态改变
2023-11-10 14:18:46.666 13917-13917 qingshan E MOBILE, isConnect= true
2023-11-10 14:18:46.666 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:18:46.666 13917-13917 qingshan E 网络状态改变
2023-11-10 14:18:46.666 13917-13917 qingshan E MOBILE, isConnect= true
2023-11-10 14:18:46.666 13917-13917 qingshan E WIFI, isConnect= false
有时日志如下:
2023-11-10 14:25:03.460 13917-13917 qingshan E 网络状态改变
2023-11-10 14:25:03.461 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:25:03.461 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:25:03.461 13917-13917 qingshan E 网络状态改变
2023-11-10 14:25:03.462 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:25:03.462 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:25:03.527 13917-13917 qingshan E 网络状态改变
2023-11-10 14:25:03.528 13917-13917 qingshan E MOBILE, isConnect= true
2023-11-10 14:25:03.528 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:25:03.528 13917-13917 qingshan E 网络状态改变
2023-11-10 14:25:03.528 13917-13917 qingshan E MOBILE, isConnect= true
2023-11-10 14:25:03.528 13917-13917 qingshan E WIFI, isConnect= false
注意:先关 wifi 再关数据时,先打印上面(“数据流量、wifi 全开,仅关闭wifi”场景)日志,再打印下面日志。
2023-11-10 14:21:58.081 13917-13917 qingshan E 网络状态改变
2023-11-10 14:21:58.082 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:21:58.082 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:21:58.083 13917-13917 qingshan E 网络状态改变
2023-11-10 14:21:58.083 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:21:58.083 13917-13917 qingshan E WIFI, isConnect= false
2023-11-10 14:31:21.285 13917-13917 qingshan E 网络状态改变
2023-11-10 14:31:21.286 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:31:21.286 13917-13917 qingshan E WIFI, isConnect= true
2023-11-10 14:31:21.287 13917-13917 qingshan E 网络状态改变
2023-11-10 14:31:21.287 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:31:21.287 13917-13917 qingshan E WIFI, isConnect= true
2023-11-10 14:31:21.317 13917-13917 qingshan E 网络状态改变
2023-11-10 14:31:21.319 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:31:21.319 13917-13917 qingshan E WIFI, isConnect= true
2023-11-10 14:31:21.319 13917-13917 qingshan E 网络状态改变
2023-11-10 14:31:21.320 13917-13917 qingshan E MOBILE, isConnect= false
2023-11-10 14:31:21.320 13917-13917 qingshan E WIFI, isConnect= true
要求 android sdk >=24
用于监听“系统默认网络”发生变更。
请勿在回调中调用 ConnectivityManager 的同步方法来查找新可用网络的属性,因为这会受到竞态条件的影响。例如:在 onLost() 回调中调用 connectivityManager.getNetworkCapabilities()。
class CustomApplication: Application() { override fun onCreate() { super.onCreate() //这里模拟工具类场景:全局一个监听,然后在工具类中分发。 getSystemService(ConnectivityManager::class.java).apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerDefaultNetworkCallback(object : NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) Log.e("qingshan", "def -> onAvailable") } override fun onLost(network: Network) { super.onLost(network) Log.e("qingshan", "def -> onLost") } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { super.onCapabilitiesChanged(network, networkCapabilities) Log.e("qingshan", "def -> 可正常访问网络 = ${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)} " + "& 数据连接 = ${networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)} " + "& wifi连接= ${networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)}") } }) } } } }
2023-11-10 15:22:31.427 8342-12273 qingshan E def -> onAvailable
2023-11-10 15:22:31.427 8342-12273 qingshan E def -> 可正常访问网络 = true & 数据连接 = false & wifi连接= true
2023-11-10 15:30:26.103 8342-12273 qingshan E def -> onLost
2023-11-10 15:30:26.150 8342-12273 qingshan E def -> onAvailable
2023-11-10 15:30:26.151 8342-12273 qingshan E def -> 可正常访问网络 = true & 数据连接 = true & wifi连接= false
注意:先关 wifi 再关数据时,先打印上面(“数据流量、wifi 全开,仅关闭wifi”场景)日志,再打印下面日志。
2023-11-10 15:35:42.923 8342-12273 qingshan E def -> onLost
2023-11-10 15:33:05.596 8342-12273 qingshan E def -> onAvailable
2023-11-10 15:33:05.596 8342-12273 qingshan E def -> 可正常访问网络 = true & 数据连接 = false & wifi连接= true
有时日志如下:
2023-11-10 15:39:22.644 8342-12273 qingshan E def -> onAvailable
2023-11-10 15:39:22.645 8342-12273 qingshan E def -> 可正常访问网络 = false & 数据连接 = true & wifi连接= false
2023-11-10 15:39:22.842 8342-12273 qingshan E def -> 可正常访问网络 = true & 数据连接 = true & wifi连接= false
用于监听所有网络发生变更。
请勿在回调中调用 ConnectivityManager 的同步方法来查找新可用网络的属性,因为这会受到竞态条件的影响。例如:在 onLost() 回调中调用 connectivityManager.getNetworkCapabilities()。
class CustomApplication: Application() { override fun onCreate() { super.onCreate() //这里模拟工具类场景:全局一个监听,然后在工具类中分发。 getSystemService(ConnectivityManager::class.java).apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerNetworkCallback(NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) .build(), object : NetworkCallback(){ override fun onAvailable(network: Network) { super.onAvailable(network) Log.e("qingshan", "all -> onAvailable") } override fun onLost(network: Network) { super.onLost(network) Log.e("qingshan", "all -> onLost") } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { super.onCapabilitiesChanged(network, networkCapabilities) Log.e("qingshan", "all -> 可正常访问网络 = ${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)} " + "& 数据连接 = ${networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)} " + "& wifi连接= ${networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)}") } }) } } } }
2023-11-10 17:24:37.153 10713-6397 qingshan E all -> onAvailable
2023-11-10 17:24:37.153 10713-6397 qingshan E all -> 可正常访问网络 = true & 数据连接 = false & wifi连接= true
2023-11-10 17:24:37.155 10713-6397 qingshan E all -> onAvailable
2023-11-10 17:24:37.155 10713-6397 qingshan E all -> 可正常访问网络 = true & 数据连接 = true & wifi连接= false
2023-11-10 17:26:28.243 10713-6397 qingshan E all -> onLost
2023-11-10 17:30:43.302 10713-6397 qingshan E all -> onLost
2023-11-10 17:30:45.464 10713-6397 qingshan E all -> 可正常访问网络 = true & 数据连接 = true & wifi连接= false
先关wifi,再关数据流量,日志如下:
2023-11-10 17:36:19.335 10713-6397 qingshan E all -> onLost
2023-11-10 17:36:19.475 10713-6397 qingshan E all -> 可正常访问网络 = true & 数据连接 = true & wifi连接= false
2023-11-10 17:36:20.802 10713-6397 qingshan E all -> onLost
先关数据流量,再关wifi,日志如下:
2023-11-10 17:37:20.487 10713-6397 qingshan E all -> onLost
2023-11-10 17:37:22.176 10713-6397 qingshan E all -> onLost
2023-11-10 17:33:42.284 10713-6397 qingshan E all -> onAvailable
2023-11-10 17:33:42.284 10713-6397 qingshan E all -> 可正常访问网络 = true & 数据连接 = false & wifi连接= true
2023-11-10 17:27:49.875 10713-6397 qingshan E all -> onAvailable
2023-11-10 17:27:49.876 10713-6397 qingshan E all -> 可正常访问网络 = true & 数据连接 = true & wifi连接= false
2023-11-10 17:27:49.878 10713-6397 qingshan E all -> 可正常访问网络 = true & 数据连接 = true & wifi连接= false
根据上面的实际运行效果可以得知:
所以,综合上述,得出如下工具类实现:
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.os.Build import android.os.Handler import android.os.Looper sealed class ConnectType(val value: Int) { object Mobile : ConnectType(0) object Wifi : ConnectType(1) object None : ConnectType(-1) companion object { fun convert2Type(value: Int): ConnectType { return when (value) { Mobile.value -> Mobile Wifi.value -> Wifi else -> None } } } } object NetConnectManager { private var mConnectivityManager: ConnectivityManager? = null private val mainHandler = Handler(Looper.getMainLooper()) private val mNetTypeListener = mutableListOf<(type: ConnectType) -> Unit>() private val mNetStateListener = mutableListOf<(isAvailable: Boolean) -> Unit>() private var mCurrentConnectType: ConnectType? = null private var mIsNetAvailable: Boolean? = null /** * 初始化 */ fun init(context: Context) { mConnectivityManager = context.getSystemService(ConnectivityManager::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mConnectivityManager?.registerDefaultNetworkCallback(DefaultNetConnectCallback()) } else { context.registerReceiver( NetConnectReceiver(), IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) ) } } /** * 注册网络类型监听 */ fun addNetTypeChangeListener(listener: (type: ConnectType) -> Unit) { mNetTypeListener.add(listener) } /** * 反注册网络类型监听 */ fun removeNetTypeChangeListener(listener: (type: ConnectType) -> Unit) { mNetTypeListener.remove(listener) } /** * 注册网络状态监听 */ fun addNetStatusChangeListener(listener: (isAvailable: Boolean) -> Unit) { mNetStateListener.add(listener) } /** * 反注册网络状态监听 */ fun removeNetStatusChangeListener(listener: (isAvailable: Boolean) -> Unit) { mNetStateListener.remove(listener) } /** * 获取当前网络类型 */ fun getConnectType(): ConnectType { if (mConnectivityManager == null) { throw UninitializedPropertyAccessException("请先调用init()初始化") } return mCurrentConnectType ?: mConnectivityManager?.getNetworkCapabilities( mConnectivityManager?.activeNetwork ).let { return if (it?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true) { ConnectType.Mobile } else if (it?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true) { ConnectType.Wifi } else { ConnectType.None } } } /** * 获取当前是否网络已连接 */ fun isConnected(): Boolean { if (mConnectivityManager == null) { throw UninitializedPropertyAccessException("请先调用init()初始化") } return (mIsNetAvailable ?: mConnectivityManager?.getNetworkCapabilities(mConnectivityManager?.activeNetwork) ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) == true } private class DefaultNetConnectCallback : ConnectivityManager.NetworkCallback() { override fun onLost(network: Network) { super.onLost(network) mCurrentConnectType = ConnectType.None mainHandler.postDelayed({ if (mCurrentConnectType == ConnectType.None && mIsNetAvailable == true) { mIsNetAvailable = false mNetStateListener.forEach { it.invoke(false) } mNetTypeListener.forEach { it(ConnectType.None) } } }, 500) } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { super.onCapabilitiesChanged(network, networkCapabilities) mainHandler.post { val isConnected = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) val isCellular = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) val isWifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) if (isConnected) { val newConnectType = if (isCellular) ConnectType.Mobile else if (isWifi) ConnectType.Wifi else ConnectType.None if (mIsNetAvailable == null || mIsNetAvailable == false) { mIsNetAvailable = true mNetStateListener.forEach { it(true) } } if (mCurrentConnectType != newConnectType) { mCurrentConnectType = newConnectType mNetTypeListener.forEach { it(newConnectType) } } } } } } private class NetConnectReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val activityNetworkInfo = context?.getSystemService(ConnectivityManager::class.java)?.allNetworkInfo?.filter { (it.type == ConnectType.Mobile.value || it.type == ConnectType.Wifi.value) && it.isConnected }?.firstOrNull() if (activityNetworkInfo != null) { if (mIsNetAvailable == null || mIsNetAvailable == false) { mIsNetAvailable = true mNetStateListener.forEach { it(true) } } ConnectType.convert2Type(activityNetworkInfo.type).let { connectType -> if (connectType != mCurrentConnectType) { mCurrentConnectType = connectType mNetTypeListener.forEach { it(connectType) } } } return } mCurrentConnectType = ConnectType.None mainHandler.postDelayed({ if (mCurrentConnectType == ConnectType.None && mIsNetAvailable == true) { mIsNetAvailable = false mNetStateListener.forEach { it(false) } mNetTypeListener.forEach { it(ConnectType.None) } } }, 500) } } }
测试代码:
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.e("qingshan", "网络是否连接= ${NetConnectManager.isConnected()} & 网络类型= ${NetConnectManager.getConnectType()}")
NetConnectManager.addNetTypeChangeListener {
Log.e("qingshan", "网络类型[监听]= $it")
}
NetConnectManager.addNetStatusChangeListener {
Log.e("qingshan", "网络是否已连接[监听]= $it")
}
}
}
qingshan E 网络是否连接= false & 网络类型= com.stefan.simpleskin.ConnectType$None@6f21c25
qingshan E 网络是否连接= true & 网络类型= com.stefan.simpleskin.ConnectType$Wifi@34771fa
qingshan E 网络类型[监听]= com.stefan.simpleskin.ConnectType$Wifi@34771fa
qingshan E 网络类型[监听]= com.stefan.simpleskin.ConnectType$Mobile@cf38ed1
qingshan E 网络是否已连接[监听]= false
qingshan E 网络类型[监听]= com.stefan.simpleskin.ConnectType$None@fddad36
qingshan E 网络类型[监听]= com.stefan.simpleskin.ConnectType$Wifi@34771fa
读取网络状态 | Connectivity | Android Developers
Hi,我是“青杉”,您可以通过如下方式关注我:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。