Android网络变化全局监听

Posted Android-kongqw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android网络变化全局监听相关的知识,希望对你有一定的参考价值。

androidNetworkMonitor

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8HuGi6bF-1582728182498)(https://jitpack.io/v/kongqw/NetworkMonitor.svg)]

Android 全局网络变化监听

GitHub的地址

How to

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.0.1'

使用

初始化

Application中初始化

NetworkMonitorManager.getInstance().init(this)

注册与反注册

在需要监听网络状态的页面进行注册与反注册

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.**  *; 

以上是关于Android网络变化全局监听的主要内容,如果未能解决你的问题,请参考以下文章

android耳机插拔监听做不了全局注册吗

android怎么设置显示监听

小程序监听 globalData 全局对象变化

Flutter-手机网络状态监听

AndroidNetworkWatcher:简化网络监听业务代码

Android中的全局监听方式