Android 全局网络变化监听
To get a Git project into your build:
Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.kongqw:NetworkMonitor:1.2.0'
}
在Application
中初始化
NetworkMonitorManager.getInstance().init(this)
或
/**
* 初始化
* @param application 上下文
* @param jitterTime 设置抖动时间(即多久之后网络状态没有发生变化,才回调网络状态,单位:毫秒,默认1500毫秒)
*/
NetworkMonitorManager.getInstance().init(this, 1_500)
在需要监听网络状态的页面进行注册与反注册
NetworkMonitorManager.getInstance().register(this)
NetworkMonitorManager.getInstance().unregister(this)
@NetworkMonitor
fun onNetWorkStateChange(networkState: NetworkState) {
when (networkState) {
NetworkState.NONE -> {
// TODO 暂无网络
}
NetworkState.WIFI -> {
// TODO WIFI网络
}
NetworkState.CELLULAR -> {
// TODO 蜂窝网络
}
}
}
也可以监听指定网络状态,例如
@NetworkMonitor(monitorFilter = [NetworkState.NONE])
fun onNetWorkStateChangeNONE(networkState: NetworkState) {
// TODO 网络断开时回调
}
@NetworkMonitor(monitorFilter = [NetworkState.WIFI])
fun onNetWorkStateChange1(networkState: NetworkState) {
// TODO WIFI连接上的时候回调
}
@NetworkMonitor(monitorFilter = [NetworkState.WIFI, NetworkState.CELLULAR])
fun onNetWorkStateChange2(networkState: NetworkState) {
// TODO 连接上WIFI或蜂窝网络的时候回调
}
val hasNetworkCapability: Boolean = NetworkStateUtils.hasNetworkCapability(applicationContext)
val networkState: NetworkState = NetworkStateUtils.getNetworkState(applicationContext)
-keepattributes *Annotation*
-keepclassmembers class * {
@com.kongqw.network.monitor.interfaces.NetworkMonitor <methods>;
}
-keep class com.kongqw.network.monitor.** { *; }